Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx: How can I match all numbers greater than 49?

I'm somewhat new to regular expressions and am writing validation for a quantity field where regular expressions need to be used.

How can I match all numbers greater than or equal to 50?

I tried

 [5-9][0-9]+ 

but that only matches 50-99. Is there a simple way to match all possible numbers greater than 49? (only integers are used)

like image 882
Maxx Avatar asked Dec 21 '11 15:12

Maxx


People also ask

How do I match a range of numbers in regex?

With regex you have a couple of options to match a digit. You can use a number from 0 to 9 to match a single choice. Or you can match a range of digits with a character group e.g. [4-9]. If the character group allows any digit (i.e. [0-9]), it can be replaced with a shorthand (\d).

What does ?= * Mean in regex?

?= is a positive lookahead, a type of zero-width assertion. What it's saying is that the captured match must be followed by whatever is within the parentheses but that part isn't captured. Your example means the match needs to be followed by zero or more characters and then a digit (but again that part isn't captured).

What does the regex 0 9 ]+ do?

In this case, [0-9]+ matches one or more digits. A regex may match a portion of the input (i.e., substring) or the entire input. In fact, it could match zero or more substrings of the input (with global modifier). This regex matches any numeric substring (of digits 0 to 9) of the input.

Does * match everything in regex?

Throw in an * (asterisk), and it will match everything. Read more. \s (whitespace metacharacter) will match any whitespace character (space; tab; line break; ...), and \S (opposite of \s ) will match anything that is not a whitespace character.


2 Answers

The fact that the first digit has to be in the range 5-9 only applies in case of two digits. So, check for that in the case of 2 digits, and allow any more digits directly:

^([5-9]\d|\d{3,})$ 

This regexp has beginning/ending anchors to make sure you're checking all digits, and the string actually represents a number. The | means "or", so either [5-9]\d or any number with 3 or more digits. \d is simply a shortcut for [0-9].

Edit: To disallow numbers like 001:

^([5-9]\d|[1-9]\d{2,})$ 

This forces the first digit to be not a zero in the case of 3 or more digits.

like image 196
pimvdb Avatar answered Sep 22 '22 11:09

pimvdb


I know there is already a good answer posted, but it won't allow leading zeros. And I don't have enough reputation to leave a comment, so... Here's my solution allowing leading zeros:

First I match the numbers 50 through 99 (with possible leading zeros):

0*[5-9]\d 

Then match numbers of 100 and above (also with leading zeros):

0*[1-9]\d{2,} 

Add them together with an "or" and wrap it up to match the whole sentence:

^0*([1-9]\d{2,}|[5-9]\d)$ 

That's it!

like image 38
Tiago Avatar answered Sep 25 '22 11:09

Tiago