Hi,
I want to match against Strings such as AhKs
& AdKs
(i.e. two cards Ah = Ace of Hearts). I want to match two off-suit cards with a regex, what I currently have is "^[AKQJT2-9][hscd]{2}$"
, but this could match hands such as AhKh
(suited) and AhAh
. Is there a way to possibly use backreferences to say the second [hscd]
cannot be the same as the firs (similarly for [AKQJT2-9]
)
views:
68answers:
4
+4
A:
Try this regular expression:
^[AKQJT2-9]([hscd])[AKQJT2-9](?!\1)[hscd]$
Here a negative look-ahead assertion (?!…)
is used to disallow the fourth character to be the same as the second (match of first grouping).
But if the regular expression implementation does not support look-around assertions, you will probably need to expand it to this:
^[AKQJT2-9](h[AKQJT2-9][scd]|s[AKQJT2-9][hcd]|c[AKQJT2-9][hsd]|d[AKQJT2-9][hsc])$
Gumbo
2010-03-21 13:54:49
Beat me by 6 seconds! :D
Max Shawabkeh
2010-03-21 13:55:34
+5
A:
Not perfectly elegant, but works:
^[AKQJT2-9]([hscd])[AKQJT2-9](?!\1)[hscd]$
Max Shawabkeh
2010-03-21 13:54:55
+1 that's very elegant actually. My version was going to be much uglier. :)
cletus
2010-03-21 13:57:20
+1
A:
a negative lookahead comes to the rescue
/^[AKQJT2-9]([hscd])[AKQJT2-9](?!\1)[hscd]$/
:( too late.
stereofrog
2010-03-21 13:55:23
+1
A:
Yes. Use back-reference together with a negative look-ahead.
^([AKQJT2-9])([hscd])(?!\1)(?!.\2)[AKQJT2-9][hscd]$
KennyTM
2010-03-21 13:55:36