考虑到text = "car price is $2017 and manufactured in 2017 and make is Honda",我正试图编写一个与2017年(制造业年)相匹配的指标。为此,我使用了负查找模式,但匹配的字符串总是第一个2017。
我使用的代码是re.search('(?<!\$)2017', text).group(),也使用了re.search('(?<!$)2017', text).group() (没有\),但没有成功。
任何关于我做错了什么的建议。
发布于 2017-11-06 07:44:07
为了匹配2017的第二个实例,您不需要负查找。
您可以使用非贪婪的量词:
^.*?2017.*?(2017)第二个实例在第一组中捕获。
代码:
>>> str = 'car price is $2017 and manufactured in 2017 and make is Honda'
>>> print re.findall(r'^.*?2017.*?(2017)', str)
['2017']发布于 2017-11-06 07:44:56
您缺少的是r,它指示原始字符串。
>>> re.search(r'(?<!\$)2017', text).group()
'2017'加上这个,你的代码就能工作了。
https://stackoverflow.com/questions/47131936
复制相似问题