regex to check string is certain length
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
精彩评论