1

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?

2 Answers 2

5

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}$/
Sign up to request clarification or add additional context in comments.

2 Comments

That's great, thanks. I did the recommended reading and realized that an even better regex would be /\A\d{11}\Z/ but that's just being picky.
@brad True. \b\d{11}\b is yet another way.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.