Some people, when confronted with a
problem, think “I know, I'll use
regular expressions.” Now they have
two problems.. - Jamie Zawinski
1997
In all seriousness, you are trying to do something that Regular Expressions aren't intended to do, which is perform logic. What you are asking is, does this string of characters contain a number, which is fine and if it does, is it >= 0 && <= 100
which isn't something a regular expression can or should be doing.
While the expression ^(\d{1,2}|100)%?$ will work to tell you if the input matches the pattern, and let you pull the number out using the group. The fact that the result falls into the >=0 && <= 100
range is a side effect. This apparent range checking behavior won't work for any other arbitrary range of numbers. Side effects should be avoided for maintainable code.
Is it the optimal solution? Is the intention obvious from just looking at the expression? I would argue no, not without some comments describing the intent.
JavaScript
I think a better more maintainable solution would be to use the parseInt()
function and then explicitly compare the result to >= 0
and <= 100
. Explicit is Better than Implicit and is more self documenting.
Python
You will still have to resort to a regular expression to validate the format and extract only the numbers and convert that using int()
, testing against the valid range would be redundant but also more explicit. Using the regular expression might not be such a bad option in this case, as long as you comment the intention of the use of the regular expression.
