简体   繁体   中英

Python regular expression search

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

eg 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?

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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM