开发者

Regex to check that a character in range doesn't repeat

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


Not perfectly elegant, but works:

^[AKQJT2-9]([hscd])[AKQJT2-9](?!\1)[hscd]$


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


a negative lookahead comes to the rescue

/^[AKQJT2-9]([hscd])[AKQJT2-9](?!\1)[hscd]$/

:( too late.


Yes. Use back-reference together with a negative look-ahead.

^([AKQJT2-9])([hscd])(?!\1)(?!.\2)[AKQJT2-9][hscd]$
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜