问题
I'm currently using ([1-9]|1[0-2])
to represent inputs from 1 to 12. (Leading zeros not allowed.)
However it seems rather hacky, and on some days it looks outright dirty.
☞ Is there a proper in-built way to do it?
☞ What are some other ways to represent number ranges?
回答1:
I tend to go with forms like [2-9]|1[0-2]?
which avoids backtracking, though it makes little difference here. I've been conditioned by XML Schema to avoid such "ambiguities", even though regex can handle them fine.
回答2:
Yes, the correct one:
[1-9]|1[0-2]
Otherwise you don't get the 10.
回答3:
You can use:
[1-9]|1[012]
回答4:
Here is the better answer, with exact match from 1 - 12.
(^0?[1-9]$)|(^1[0-2]$)
Previous answers doesn't really work well with HTML input regex validation, where some values like '1111' or '1212' will still treat it as a valid input.
回答5:
How about:
^[1-9]|10|11|12$
Matches 0-9 or 10 or 11 or 12. thats it, nothing else is matched.
来源:https://stackoverflow.com/questions/7105146/how-to-represent-regex-number-ranges-e-g-1-to-12