nikunj2512 nikunj2512 - 2 months ago 12
Python Question

Python Regex findall But Not Including the conditional string

i have this string:

The quick red fox jumped over the lazy brown dog lazy


And i wrote this regex which gives me this:

s = The quick red fox jumped over the lazy brown dog lazy

re.findall(r'[\s\w\S]*?(?=lazy)', ss)


which gives me below output:

['The quick red fox jumped over the ', '', 'azy brown dog ', '']


But i am trying to get the output like this:

['The quick red fox jumped over the ']


Which means the regex should give me everything till it encounters the first
lazy
instead of last one and i only want to use
findall
.

Answer

Make the pattern non-greedy by adding a ?:

>>> m = re.search(r'[\s\w\S]*?(?=lazy)', s)
#                            ^
>>> m.group()
'The quick red fox jumped over the '
Comments