开发者

Regex to validate number and letter sequence

I want a regex to validate inputs of the form AABBAAA, where A is a a letter (a-z, A-Z) and B is a digit 开发者_如何学Python(0-9). All the As must be the same, and so must the Bs.


If all the A's and B's are supposed to be the same, I think the only way to do it would be:

([a-zA-Z])\1([0-9])\2\1\1\1

Where \1 and \2 refer to the first and second parenthetical groupings. However, I don't think all regex engines support this.


It's really not as hard as you think; you've got most of the syntax already.

[a-zA-Z]{2}[0-9]{2}[a-zA-Z]{3}

The numbers in braces ({}) tell how many times to match the previous character or set of characters, so that matches [a-zA-Z] twice, [0-9] twice, and [a-zA-Z] three times.

 
Edit: If you want to make sure the matched string is not part of a longer string, you can use word boundaries; just add \b to each end of the regex:

\b[a-zA-Z]{2}[0-9]{2}[a-zA-Z]{3}\b

Now "Ab12Cde" will match but "YZAb12Cdefg" will not.

 
Edit 2: Now that the question has changed, backreferences are the only way to do it. edsmilde's answer should work; however, you may need to add the word boundaries to get your final solution.

\b([a-zA-Z])\1([0-9])\2\1\1\1\b


[a-zA-Z]{2}\d{2}[a-zA-Z]{3}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜