tags:

views:

74

answers:

9

Help needed to fix one little thing in this regular expression

^\d{2}\-\d{3}\-\d{6}

Its validating this format 11-111-111111. It is working fine. but the last one (6 digits) is also validating more than 6 digits. That means if i put 11-111-11111111 (8 digits in last part), the above regex is validating it?

Can someone tell me how to limit it to 6 digits only?

+5  A: 

Put a $ at the end of the regex. $ is the string or line end anchor and will ensure that there are no more than 6 digits in the last section (since the string has to end after that).

Joey
+11  A: 

Do also mark the end of the string ($) as you did it with the start of the string (^):

^\d{2}\-\d{3}\-\d{6}$

Now the whole string has to match this pattern.

Gumbo
Come on! So many up-votes for this kind of answer?
Gumbo
+2  A: 

You want you use $ to signify the end of the line, just like you use ^ to signify the start of the line.

unholysampler
+1  A: 

I was able to do it by adding $ to the end of the regex. That will cause it to recognize only 6 digits at the end of the match.

Currently, it's matching your 8-digit entry because it starts with the first 6 digits.

Eric
A: 

Put $ at the end of your regex.

This symbol signifies "end of the expression".

Alix
A: 
(^\d{2}\-\d{3}\-\d{6})\D

will match anything with 6 digits followed by a non-digit, assuming you don't actually expect the line to end there.

Joel
A: 

If you want to catch the string even when it's not the end of a line, use

^\d{2}\-\d{3}\-\d{6}\D

to specify that the thing that comes after the 6 digits must be a non-digit.

ansate
+2  A: 
^\d{2}-\d{3}-\d{6}(?:\D|$)

The last part (?:\D|$) matches anything that is not a number or end of line

M42
A: 

The basics of your regex is there, but you need to put in the boundarys.

The following regex matches what you want and captures the number string. It is bound on both ends by a non-digit or the begin/end of string.

(?:[^\d]|^)(\d{2}-\d{3}-\d{6})(?:[^\d]|$)

Rontologist