re.search, how to extract a substring between two strings, but must be between the nearest matches

Viewed 71

Let's suppose I have a string: s = 'pa blah blah blah pa xxxtring pu'.

How can I get a string between pa and pu, but using the pa and pu that are near.

In this case I would like to get output: 'xxxstring'

I used re.search('pa (.+?) pu',s).group(1), but as a result I got 'blah blah blah pa xxxtring' which is not what I wanted.

1 Answers

I think the best solution would be to use a regex module allowing overlapping matches (regex) and get the smallest result:

$> pip3 install regex

Then you can use it as follow:

import regex as re
s = 'pa blah blah blah pa xxxtring pu'

# findall finds all occurrences
# allow overlapping with overlapped=True
res = re.findall('pa (.+?) pu', s, overlapped=True)
#=> ['blah blah blah pa xxxtring', 'xxxtring']

# Get the smallest string of matches :
result = min(res, key=len)

print(result)
#=> 'xxxtring'

I find this solution quite elegant. Please let me know if it solves your issue.

Related