Is there an ability to make a lookahead assertion non-capturing? Things like bar(?:!foo)
and bar(?!:foo)
do not work (Python).
是否有能力使前瞻断言不被捕获?像bar(?:!foo)和bar(?!:foo)这样的东西不起作用(Python)。
2 个解决方案
#1
2
If you do bar(?=ber)
on "barber", "bar" is matched, but "ber" is not captured.
如果你在“barber”上做bar(?= ber),则匹配“bar”,但不捕获“ber”。
#2
1
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:
你没有回答艾伦的问题,但我会认为他是正确的,你对一个负面的前瞻断言感兴趣。 IOW - 匹配'bar'但不是'barfoo'。在这种情况下,您可以按如下方式构造正则表达式:
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
#1
2
If you do bar(?=ber)
on "barber", "bar" is matched, but "ber" is not captured.
如果你在“barber”上做bar(?= ber),则匹配“bar”,但不捕获“ber”。
#2
1
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:
你没有回答艾伦的问题,但我会认为他是正确的,你对一个负面的前瞻断言感兴趣。 IOW - 匹配'bar'但不是'barfoo'。在这种情况下,您可以按如下方式构造正则表达式:
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