Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for matching a pokerhand (Java)

Tags:

java

regex

Regex rookie here.

I need a regex that matches a specific poker hand (Full House - a poker hand containing three cards of one rank and two cards of another rank) It should recognize it as a full house with the cards in any arbitrary order and with all card ranks (23456789TJQKA) and suits (SHDC)

I'm not even sure regex is the right tool for this, so please tell me if you think I should do something else :)

an example string could look like

"KD KC AH AC AD"

(King of Diamonds, King of Clubs, Ace of Hearts, Ace of Clubs, Ace of Diamonds)

I've come up with this ugly regex

(?=.*(([2-9TJQKA])[SHDC]).*\2[SHDC].*\2[SHDC])(?=.*(?!\2)(([2-9TJQKA])[SHDC]).*\4[SHDC].*\4[SHDC]).*

but it does not seem to do the job.

like image 234
Boris Grunwald Avatar asked Mar 13 '26 14:03

Boris Grunwald


1 Answers

this should match 'full houses': (edit: and is really just your original regex fixed up to ignore the suit)

(?=.*([2-9TJQKA])[SHDC].*\1[SHDC].*\1[SHDC])(?=.*((?!\1)[2-9TJQKA])[SHDC].*\2[SHDC])

It looks for the "3" sequence with the first lookahead. the second lookahead, which is looking for the "2" sequence, includes a negative lookahead within it to prevent duplicate matching. The regex is composed entirely of two lookaheads, which prevent the issues that would arise if we actually matched (and moved the pointer ahead) any characters - both of these subpatterns are free to match anywhere in the string.

online demo here

like image 163
Scott Weaver Avatar answered Mar 16 '26 03:03

Scott Weaver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!