开发者

How to fix this regex?

Help needed to fix one little thing in this regular expression

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

Its validating this format 11-111-11111开发者_如何学Python1. 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?


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.


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).


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


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.


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.


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

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


Put $ at the end of your regex.

This symbol signifies "end of the expression".


(^\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.


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]|$)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜