Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to match a number which is less than or equal to 100?

Tags:

regex

perl

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, 130, 150, 999, etc.

like image 224
chanti Avatar asked Jun 13 '12 09:06

chanti


People also ask

How do I match a range of numbers in regex?

The regex [0-9] matches single-digit numbers 0 to 9. [1-9][0-9] matches double-digit numbers 10 to 99. Something like ^[2-9][1-6]$ matches 21 or even 96! Any help would be appreciated.

What is regex for numbers?

Definition and Usage. The [0-9] expression is used to find any character between the brackets. The digits inside the brackets can be any numbers or span of numbers from 0 to 9. Tip: Use the [^0-9] expression to find any character that is NOT a digit.

What is D regex?

\d (digit) matches any single digit (same as [0-9] ). The uppercase counterpart \D (non-digit) matches any single character that is not a digit (same as [^0-9] ). \s (space) matches any single whitespace (same as [ \t\n\r\f] , blank, tab, newline, carriage-return and form-feed).


2 Answers

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 " 
like image 162
Cylian Avatar answered Sep 25 '22 18:09

Cylian


How about this for the regex:

^([0-9]|[1-9][0-9]|100)$ 

this would validate 7, 82, 100 for examples, but would not validate 07 or 082.

Check this out for more information (and variations including zero prefixing) on number range checking


If you need to cater for floating point numbers you should read this, here is an expression you can use:

Floating point: ^[-+]?([0-9]|[1-9][0-9]|100)*\.?[0-9]+$

like image 23
musefan Avatar answered Sep 25 '22 18:09

musefan