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}
Which 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.
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