开发者

regex to check string is certain length

开发者 https://www.devze.com 2022-12-24 16:41 出处:网络
I am trying to write a regex to match pairs of cards (AA, KK, QQ ... 22) and I have the regex ([AKQJT2-9])\\1. The problem I have is that this regex will match AA as well as AAbc etc. Is there a way t

I am trying to write a regex to match pairs of cards (AA, KK, QQ ... 22) and I have the regex ([AKQJT2-9])\1. The problem I have is that this regex will match AA as well as AAbc etc. Is there a way to write the regex such that I can specify I want to match ([AKQJT2-9])\1 and only that (i.e. no more characters af开发者_如何学Cter).


Enclose the regex in ^ and $:

^([AKQJT2-9])\1$

^ is the "start-of-string" anchor, and $ is the "end-of-string" anchor. If your regex flavor supports it, \A and \Z might be an even better choice since ^ and $ can also match start/end of a line in a multiline string, depending on your regex engine and configuration.


You mean, like this ?

^([AKQJT2-9])\1$

It will only match if the string is "AA", "KK", …

If you want to capture both characters, but not the rest of the string, you'll have to use another parenthesis

($match,$unused) = $string ~= (([AKQJT2-9])\2); # in perl
0

精彩评论

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