带有或不带小数的百分比的正则表达式

Im trying to use a regular expression to validate strings like:

1 %
12,25 %
99,99 %
100 %
100,00 %

Tried with this one from here

^(100\,00|[1-9]?\d\,\d{2}) %$

but i need the decimals to be optional and this one fails with strings like "90 %"

Thank you in advance,

/^(10{2}(?:,0{2})?|[1-9]?\d(?:,\d{2})?) %$/

The pattern allows a percentage of 100,00 or a 1 or 2 digit number (2-digit not starting with 0) optionally followed by a comma and 2 digits.

See Pattern Demo for matching, explanation, and efficiency.

Bonus features:

My pattern uses quantifiers on repeated characters to improve performance.
It doesn't use escaping slashes on commas -- they're not necessary.
It doesn't use more than one capture group, following the OP's pattern design.

So, make the optional parts a capture group with (...) and declare it optional by adding ?

Result:

^(100(\,00)?|[1-9]?\d(\,\d{2})?) %$

Matches:

  • 10 %
  • 10,20 %
  • 100,00 %
  • 100 %

Won't match:

  • 10,2 %
  • 200 %