0

(From a previous question I asked) a way to find if a poker hand that has 2-, 3-, or 4-of-a-kind would be with a regex like the following:

REGEX = (.)(.*?\1){1,3}
re.search(REGEX, 'JAJ24').group(1)
'J'

For example, it works at the following regex101 link here: https://regex101.com/r/MAugJC/3.

How could I also assert that the length of the string itself is exactly 5 chars? Without doing another regex, the only thing that I could think of was in doing a lookaround that totals 5 chars, for example, lookahead 5 or lookahead 4 + lookbehind 1, etc. Would it be possible to do this in a regex with another (simpler) method?

Here are some examples of what it should and should not match:

2Q33K # yes, 3's
KK238 # yes, K's
JAJ29 # yes, J's
K246K # yes, K's
KJKKK # yes, K's
3JKA9 # no pair
94822 # yes, 2's
94228 # yes, 2's
22849 # yes, 2's
3JKA9K8 # no, length != 5
samuelbrody1249
  • 4,379
  • 1
  • 15
  • 58
  • You can prepend `(?=.{5}$)` – ctwheels Nov 12 '19 at 00:28
  • @ctwheels right, but what if the first pair occurs after the first string char? Then the lookahead would only have four chars remaining -- it wouldn't match something like `94822` – samuelbrody1249 Nov 12 '19 at 00:30
  • I'm not sure the question is clear, could you expand it to include examples of what to and what not to match? Also, any code outside of stackoverflow should be included in your question (e.g. if a site goes down permanently, that information is lost) – ctwheels Nov 12 '19 at 00:32
  • Maybe use `(?=.{5}$).*((.)(?:.*?\2){1,3})` and access your match in group #1? I'm not sure what's the point of `{1,3}` here though. – 41686d6564 stands w. Palestine Nov 12 '19 at 00:37
  • @ctwheels I've updated the question with a few example strings to match against. – samuelbrody1249 Nov 12 '19 at 00:41
  • @ctwheels I've got it to work using your example above and putting anchors on it, for example: https://regex101.com/r/MAugJC/4 – samuelbrody1249 Nov 12 '19 at 00:45

0 Answers0