Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking a number range with regular expressions

Tags:

I'm using a regular expression to validate a certain format in a string. This string will become a rule for a game.

Example: "DX 3" is OK according to the rule, but "DX 14" could be OK too... I know how to look at the string and find one or more "numbers", so the problem is that the regex will match 34 too, and this number is out of "range" for the rule...

Am I missing something about the regex to do this? Or is this not possible at all?

like image 995
mrs1986 Avatar asked Oct 22 '11 18:10

mrs1986


People also ask

How do you find the range of a number in regex?

To show a range of characters, use square backets and separate the starting character from the ending character with a hyphen. For example, [0-9] matches any digit. Several ranges can be put inside square brackets. For example, [A-CX-Z] matches 'A' or 'B' or 'C' or 'X' or 'Y' or 'Z'.

How do you define a range in regex?

Range in Regular Expressions Ranges of characters can be indicated by giving two characters and separating them by a '-', for example [a-z] will match any lowercase ASCII letter, [0-5][0-9] will match all the two-digits numbers from 00 to 59.

Can you use regex for numbers?

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].

What is the difference between () and [] in regex?

In other words, square brackets match exactly one character. (a-z0-9) will match two characters, the first is one of abcdefghijklmnopqrstuvwxyz , the second is one of 0123456789 , just as if the parenthesis weren't there. The () will allow you to read exactly which characters were matched.


1 Answers

Unfortunately there's no easy way to define ranges in regex. If you are to use the range 1-23 you'll end up with a regex like this:

([1-9]|1[0-9]|2[0-3]) 

Explanation:

  1. Either the value is 1-9
  2. or the value starts with 1 and is followed with a 0-9
  3. or the value starts with 2 and is followed with a 0-3
like image 70
Marcus Avatar answered Oct 02 '22 20:10

Marcus