I want to match a number which is less than or equal to 100, it can be anything within 0-100, but the regex should not match for a number which is greater than 100 like 120,
This regEx matches the numbers 0-100 diapason and disallow numbers like 001:
\b(0|[1-9][0-9]?|100)\b
this matches 0 to 100
^0*([0-9]|[1-8][0-9]|9[0-9]|100)$
regex for this
perl -le 'for (qw/0 1 19 32.4 100 77 138 342.1/) { print "$_ is ", /^(?:100|\d\d?)$/ ? "valid input" : "invalid input"}'
Use Code Assertions if you need a regex (eventually):
/^(.+)$(??{$^N>=0 && $^N<=100 ? '':'^'})/
Test:
my @nums = (-1, 0, 10, 22, 1e10, 1e-10, 99, 101, 1.001e2);
print join ',', grep
/^(.+)$(??{$^N>=0 && $^N<=100 ? '':'^'})/,
@nums
Result:
0,10,22,1e-010,99
(==> Here is sth. to learn about code assertions).
My practical Advice.
Personally, I would refrain writing such a complex regex altogether. What if your number changes from 100 to 200 in near future. Your regex will have to change significantly and it might be even harder to write. All the above solutions are NOT self explanatory and you will have to complement it with a comment in your code. That's a smell.
Readability matters. Code is for humans and not for machines.
Why not write some code around it and keep regex dead simple to understand.
Try this
\b(0*(?:[1-9][0-9]?|100))\b
Explanation
"
\b # Assert position at a word boundary
( # Match the regular expression below and capture its match into backreference number 1
0 # Match the character “0” literally
* # Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
(?: # Match the regular expression below
# Match either the regular expression below (attempting the next alternative only if this one fails)
[1-9] # Match a single character in the range between “1” and “9”
[0-9] # Match a single character in the range between “0” and “9”
? # Between zero and one times, as many times as possible, giving back as needed (greedy)
| # Or match regular expression number 2 below (the entire group fails if this one fails to match)
100 # Match the characters “100” literally
)
)
\b # Assert position at a word boundary
"