regular expression matching a string that is followed with another string without capturing the latter

跟風遠走 提交于 2019-12-10 05:38:33

问题


Is there an ability to make a lookahead assertion non-capturing? Things like bar(?:!foo) and bar(?!:foo) do not work (Python).


回答1:


If you do bar(?=ber) on "barber", "bar" is matched, but "ber" is not captured.




回答2:


You didn't respond to Alan's question, but I'll assume that he's correct and you're interested in a negative lookahead assertion. IOW - match 'bar' but NOT 'barfoo'. In that case, you can construct your regex as follows:

myregex =  re.compile('bar(?!foo)')

for example, from the python console:

>>> import re
>>> myregex =  re.compile('bar(?!foo)')
>>> m = myregex.search('barfoo')
>>> print m.group(0)                <=== Error here because match failed
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'
>>> m = myregex.search('bar')    
>>> print m.group(0)                <==== SUCCESS!
bar


来源:https://stackoverflow.com/questions/9864493/regular-expression-matching-a-string-that-is-followed-with-another-string-withou

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!