【问题标题】:Negative lookbehind is not matching负后视不匹配
【发布时间】:2017-11-06 07:38:05
【问题描述】:

考虑到text = "car price is $2017 and manufactured in 2017 and make is Honda",我正在尝试编写一个匹配第二个 2017 年(制造年)的正则表达式。为此,我使用了否定的lookbehind模式,但匹配的字符串始终是第一个 2017。

我使用的代码是re.search('(?<!\$)2017', text).group(),也使用了re.search('(?<!$)2017', text).group()(没有\)但没有成功。

任何指向我做错了什么的指针。

【问题讨论】:

标签: python regex python-2.7


【解决方案1】:

您不需要否定的后视来匹配2017 的第二个实例。

你可以使用非贪心量词:

^.*?2017.*?(2017)

RegEx Demo

第二个实例在组号中被捕获。 1

代码:

>>> str = 'car price is $2017 and manufactured in 2017 and make is Honda'
>>> print re.findall(r'^.*?2017.*?(2017)', str)
['2017']

【讨论】:

    【解决方案2】:

    你缺少的是r,它表示原始字符串

    >>> re.search(r'(?<!\$)2017', text).group()
    '2017'
    

    添加它,您的代码就可以工作了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-02
      • 2022-12-14
      相关资源
      最近更新 更多