Why doesn't this ruby regex work? -


i have simple regex task has left me confused (and when thought starting hang of them too). want check string consists of 11 digits. regex have used /\d{11}/. understanding give match if there (no more , no less than) 11 numeric characters (but understanding wrong).

here happens in irb:

ruby-1.9.2-p136 :018 > "33333333333" =~ /\d{11}/  => 0  ruby-1.9.2-p136 :019 > "3333333333" =~ /\d{11}/  => nil  ruby-1.9.2-p136 :020 > "333333333333" =~ /\d{11}/  => 0  

so while appropriate match 11 digit string , appropriate no-match 10 digit string, getting match on 12 digit string! have thought /\d{11,}/ regex this.

can explain misunderstanding?

without anchors, assumption "no more, no less" incorrect.

/\d{5}/  

matches

foo12345bar    ^    +---here 

and

s123456yargh13337  ^^         ^  |+---here  |  +----here  |       here--+ 

so, instead use:

/^\d{5}$/ 

Comments

Popular posts from this blog

java - SNMP4J General Variable Binding Error -

windows - Python Service Installation - "Could not find PythonClass entry" -

Determine if a XmlNode is empty or null in C#? -