I am trying to perform a regular expression that validates the following format:
- there will only be numbers separated by commas or hyphen
- there may be ranges of numbers (separated by hyphens)
- the numbers must go from 1 to 31
- that the value of the second part is greater than that of the first (this is still more complex, but if it is very difficult I will discard it)
Example of strings I would consider valid:
4.31.2-22.8
29.1-10.2-12.9
Example of invalid strings:
4.31.2-22.8,
29.1-10,-2-12-.9
29.1-50.2-12.32
The regular expression I have so far is the following:
((([1-9]|1[0-9]|2[0-9]|3[0-1])(\-([1-9]|1[0-9]|2[0-9]|3[0-1]))?)
(\,(([1-9]|1[0-9]|2[0-9]|3[0-1])(\-([1-9]|1[0-9]|2[0-9]|3[0-1]))?))*)
At the moment this expression handles the issue of hyphens and commas well, but I can't get it to handle the numbers from 10 to 31 well and the issue of the range that the second value is greater than the first I can't think of how to solve it. suggestion?
Try the following:
It's not a pretty or intuitive regular expression, but it should do what you need.
You have a demo of the regular expression here .
And also a demo with javascript below:
Note that when the regular expression starts to get complicated, it is better to use a simpler regular expression by adding some code. It is much easier to maintain.
Here below I put the same regular expression in extended format, with comments.
Finally, if you want something simpler and do not validate if the left part is less than the right part, you could use this regular expression, which is a little shorter than the one you proposed in the statement.
The idea is a bit different. Instead of allowing only what I'm interested in, here we 'allow all' (we use
\d
) and use rules to exclude cases that we don't care about.By the way, comment a couple of things in the regular expression statement:
-
should only be backslash-escaped when they are inside class characters and the hyphen is not at the end. For example, here you must escape if you want to specify hyphen:[A\-B]
, you don't need to here[AB-]
. And here neither:A-B
(?:)
instead of()
32
will find2
. You could fix this by adding^
at the beginning of your regular expression