I have a string that is always in the following pattern:
"AB AB AB AB AB " // (note the trailing space)
Where A
can be any character in "12345678TJQKA"
, and B
can be any character in "HSCD"
(basically the 52 playing cards).
How can I check if this String is for example a Royal Flush with a regex?
Some things I tried without result (just using Diamonds for now) (NOTE: I have no idea how to properly use look-aheads, look-behinds, and look-arounds, so I most likely do something everything wrong..)
^(?=AD )(?=KD )(?=QD )(?=JD )TD $
^(?=AD .*)(?=KD .*)(?=QD .*)(?=JD .*)TD .*$
^(?=AD )(?=KD )(?=QD )(?=JD )(?=TD )$
^(?=AD .*)(?=KD .*)(?=QD .*)(?=JD .*)(?=TD .*)$
^(?<=AD )(?<=KD )(?<=QD )(?<=JD )(?<=TD )$
So I want the regex to match "AD KD QD JD TD "
in any order (so including for example its reversed ("TD JD QD KD AD "
) or in this random order: "KD TD QD AD JD "
). Preferably with a capture group for D
as well so it's uniform for all four suits..
Here is an online regex tester with some test cases in case anyone want to fuddle around.
If you have a regex that not only matches for Diamond Royal Flush, but for all suits at the same time (with explanation of how it works) that would be even better. (Any other method to check for Royal Flush instead of regex is fine as well, but I'd still like to know how this can be done in regex as well, since that is where my question is mainly about.)
You can use regex to check this, though it might not be the best way to do this.
My answer has the assumption that all strings are proper entries (5 cards in your given format).
We can then use
^(?=.*J(\w))(?=.*Q\1)(?=.*T\1)(?=.*K\1)(?=.*A\1).*$
To check if it is a royal flush. We use a bunch of lookaheads to check the needed cards and in the first try match the used suit and ruse it with a backreference. We can simply use \w
to check the suit, as the identifiers of card type and suit don't overlap (even .
should be possible)