farrusete farrusete -4 years ago 54
PHP Question

Regex for percentages with or without decimals

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,

Answer Source
/^(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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download