MorganFreeFarm
MorganFreeFarm

Reputation: 3733

Python, regex - how to match second group, only if first group is matched

Input:

2SASKS6SJSQSOS

Expected Output:

2S AS KS 6S JS QS

My code:

import re

row = input()

pattern = r"([1]?[0-9]?[JQKA]?)([SHDC])"

result = ''

for (first, second) in re.findall(pattern, row):
    if first and second:
        result += first + second + ' '

print(result)

So at the moment it works, because this check do the magic:

if first and second:

Without this check it return:

2S AS KS 6S JS QS S 

because it matches second group.

I want to do this in the regex, not with if check, is it possible ? To check if first group is matched, then to match second group?

Upvotes: 1

Views: 1385

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627607

You may add a lookahead to make sure there is a digit or a J, Q, K or A letter:

import re
row = '2SASKS6SJSQSOS'
pattern = r"(?=[0-9JQKA])(1?[0-9]?[JQKA]?)([SHDC])"
result = [x.group() for x in re.finditer(pattern, row)]
print(result) # => ['2S', 'AS', 'KS', '6S', 'JS', 'QS']

Or even

result = re.findall(r"(?=[0-9JQKA])1?[0-9]?[JQKA]?[SHDC]", row)

See the Python demo

It works because the second group pattern is not overlapping with what is matched in the first group.

See the regex graph:

enter image description here

Details

  • (?=[0-9JQKA]) - a positive lookahead that requires an ASCII digit, J, Q, K or A immediately to the right of the current location
  • 1? - an optional 1
  • [0-9]? - an optional ASCII digit
  • [JQKA]? - an optional letter from the character class: J, Q, K or A
  • [SHDC] - an S, H, D or C letter.

Upvotes: 1

Related Questions