2

I was trying to search for all those phrases with the key word 'car':

e.g. text = 'alice: speed car, my red car, new car', I would like to find 'speed car', 'my red car', 'new car'.

import re
text = 'alice: speed car, my red car, new car'
regex = r'([a-zA-Z]+\s)+car'
match = re.findall(regex, text)
if match:
    print(match)

but the above code yields:

["speed ", "red ", "new "]

instead of

["speed car", "my red car", "new car"]

which is expected?

1 Answer 1

4

Problem is you're not capturing 'car' in your regex, put the whole regex inside a () and and use ?: for the inner regex to make it a non-capturing group.

>>> regex = r'((?:[a-zA-Z]+\s)+car)'
>>> text = 'alice: speed car, my red car, new car'
>>> re.findall(regex, text)
['speed car', 'my red car', 'new car']
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.