How to find all matches with a regex where part of the match overlaps

Viewed 54

I have a long .txt file. I want to find all the matching results with regex.

for example :

test_str = 'ali. veli. ahmet.'
src = re.finditer(r'(\w+\.\s){1,2}', test_str, re.MULTILINE)
print(*src)

this code returns :

<re.Match object; span=(0, 11), match='ali. veli. '>

i need;

['ali. veli', 'veli. ahmet.']

how can i do that with regex?

1 Answers

The (\w+\.\s){1,2} pattern contains a repeated capturing group, and Python re does not store all the captures it finds, it only saves the last one into the group memory buffer. At any rate, you do not need the repeated capturing group because you need to extract multiple occurrences of the pattern from a string, and re.finditer or re.findall will do that for you.

Also, the re.MULTILINE flag is not necessar here since there are no ^ or $ anchors in the pattern.

You may get the expected results using

import re
test_str = 'ali. veli. ahmet.'
src = re.findall(r'(?=\b(\w+\.\s+\w+))', test_str)
print(src)
# => ['ali. veli', 'veli. ahmet']

See the Python demo

The pattern means

  • (?= - start of a positive lookahead
    • \b - a word boundary (crucial here, it is necessary to only start capturing at word boundaries)
    • (\w+\.\s+\w+) - Capturing group 1: 1+ word chars, ., 1+ whitespaces and 1+ word chars
  • ) - end of the lookahead.
Related