【问题标题】:Python regular expression searchPython正则表达式搜索
【发布时间】:2013-08-16 00:35:26
【问题描述】:

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

例如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"]

这是预期的?

【问题讨论】:

    标签: python regex search findall


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-27
      • 2015-02-23
      • 2015-05-30
      • 2014-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多