2

我试图用关键字“汽车”搜索所有这些短语:

eg text = 'alice: speed car, my red car, new car', 我想找'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)

但上面的代码产生:

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

代替

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

哪个是预期的?

4

1 回答 1

4

问题是你没有'car'在你的正则表达式中捕获,将整个正则表达式放在 a 中()?:用于内部正则表达式以使其成为非捕获组。

>>> 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']
于 2013-08-14T07:08:23.263 回答