Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx for a string of length 0-2

Tags:

regex

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?

like image 291
James Cadd Avatar asked Feb 17 '11 21:02

James Cadd


2 Answers

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.

like image 90
Donut Avatar answered Sep 20 '22 09:09

Donut


You need to anchor the regex:

^[0-9]{0,2}$ 

Otherwise the regex will happily match substrings.

like image 42
Tim Pietzcker Avatar answered Sep 18 '22 09:09

Tim Pietzcker