Regex to check that a character in a range is not repeated

I want to match strings like AhKsand AdKs(i.e. two cards Ah = Ace of Hearts). I want to combine two cards outside the game with a regular expression, what I have now "^[AKQJT2-9][hscd]{2}$", but this may coincide with such hands as AhKh(fits) and AhAh. Is there a way to use backlinks to say that the second [hscd]cannot be the same as firs (similar for [AKQJT2-9])

+3
source share
4 answers

Try this regex:

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

(?!…) , , ( ).

look-around, , , :

^[AKQJT2-9](h[AKQJT2-9][scd]|s[AKQJT2-9][hcd]|c[AKQJT2-9][hsd]|d[AKQJT2-9][hsc])$
+4

, :

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

a negative look comes to the rescue

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

:( too late.

+1
source

Yes. Use the backlink along with a negative outlook.

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

Source: https://habr.com/ru/post/1737913/


All Articles