RegEx for a string of length 0-2
I'm trying to match a string that can be either empty or have 1 or 2 numbers in it such as the following:
"" (empty) "1" "23"
String with more numbers or non-numeric characters should not match. My closest guess is the regex:
[0-9]{0,2}
W开发者_StackOverflow社区hich I read to say "the numbers 0 through 9 occurring 0 to 2 times." However, in practice I find that regex also matches longer strings like "333". How is it possible to restrict string length in regular expressions?
Use the following regex:
^[0-9]{0,2}$
You almost had it -- the ^
and $
characters are anchors that match the beginning and end of the string, respectively.
For a more in-depth discussion on anchors, see here:
[Anchors] do not match any character at all. Instead, they match a position before, after or between characters. They can be used to "anchor" the regex match at a certain position.
You need to anchor the regex:
^[0-9]{0,2}$
Otherwise the regex will happily match substrings.
Use the metacharacters for start and end of string:
^[0-9]{0,2}$
If you don't use them, it matches anywhere in the string, and "12", which matches, is part of "123".
精彩评论