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?
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'.
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.
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].
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.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With