简体   繁体   中英

Why doesn't this ruby regex work?

I have a very simple regex task that has left me confused (and just when I thought I was starting to get the hang of them too). I just want to check that a string consists of 11 digits. The regex I have used for this is /\\d{11}/ . My understanding is that this will give a match if there are exactly (no more and no less than) 11 numeric characters (but clearly my understanding is wrong).

Here is what 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 I get an appropriate match for an 11 digit string and an appropriate no-match for a 10 digit string, I am getting a match on a 12 digit string! I would have thought /\\d{11,}/ would be the regex to do this.

Can anyone explain my misunderstanding?

Without anchors , the assumption "no more, no less" is incorrect.

/\d{5}/ 

matches

foo12345bar
   ^
   +---here

and

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

So, instead use:

/^\d{5}$/

The 12 digit string contains the substring that matches your regexp. If you want an exact match, write the regexp like this: /^\\d{11}$/ .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM