-1

I have a string representing cards in a deck, i.e. 7c9hQsKsAs

Is it possible to use Regex to specify .*x.*x.*x.*x.*x where x would specify any character (c/h/d/s) as long as the character is the same character throughout? This would be used to determine if there was a flush.

This would be used to determine if the given cards make a specific poker hand. I've considered sorting by value and suit however I would still need to specify that all suit characters are the same (i.e. value and suit sorted TcJcQcKcAd would be a royal flush).

apilsons
  • 21
  • 4
  • I wouldn't think you'd want `.*` but rather just `.`. For example, `.c.c.c.c.c` would be a flush (clubs). You could match a flush in any suit with `.([chsd]).\1.\1.\1.\1`. But a royal flush would be simple (I'll leave it as an exercise to update my example to achieve that). – lurker Feb 21 '19 at 21:41
  • @Wiktor This isn't actually a duplicate. By that logic, literally any question about back references would be a duplicate of that question. That seems far too broad to be a duplicate. – Nicole Feb 21 '19 at 22:08
  • @Nicole It is a dupe because OP has shown no attempt at solving the problem. It appears that OP just does not know about capturing groups/backreferences, and all OP needs is to learn about them. [This](https://stackoverflow.com/questions/22937618/reference-what-does-this-regex-mean) would be too broad, though still applicable. Also, see [Should “Give me a regex that does X” questions be closed?](http://meta.stackoverflow.com/questions/285733/should-give-me-a-regex-that-does-x-questions-be-closed/285739#285739) – Wiktor Stribiżew Feb 21 '19 at 22:10
  • Well, I disagree. I do see an attempt to describe the desired behavior. Not knowing about a relevant tool to solve the problem is the impetus for hundreds of thousands of questions, and not a good reason IMHO to close the question. I've asked about this here. https://meta.stackoverflow.com/questions/380471/how-broadly-are-similarities-considered-duplicates – Nicole Feb 21 '19 at 22:14

1 Answers1

1

It depends on what flavor of regex you are using, but if it supports back references, then yes:

.*(\w).*\1.*\1.*\1.*\1.*

matches...

123c234c345c456c567c678

with "c" as the first reference. The \1 says to match the first captured group.

Demo: https://regex101.com/r/Ia9Zg0/1

Even though every character (1, 2, 3, 4, 5, 6, 7, 8 and c), given the whole expression, the captured group only matches "c" because it's the only one that repeats 5 times.

You might want something more specific like:

.+([chds]).+\1.+\1.+\1.+\1

This uses + (1 or more) instead of * (0 or more) because you do require a rank (value) character before each suit character. * (0 or more) would make it optional.

Demo: https://regex101.com/r/VKbmnR/1/

Help: https://www.regular-expressions.info/backref.html

Nicole
  • 30,999
  • 11
  • 69
  • 94