当我运行在Python 2.7以下声明,为什么python正则表达式替换(A | B)不匹配按照文档?
re.search('eagle|cat', 'The cat is an animal. The eagle is bird').group()
我期待看到'eagle'
的结果按正则表达式的文档 但我发现了'cat'
。我在这里错过了什么吗?
当我运行在Python 2.7以下声明,为什么python正则表达式替换(A | B)不匹配按照文档?
re.search('eagle|cat', 'The cat is an animal. The eagle is bird').group()
我期待看到'eagle'
的结果按正则表达式的文档 但我发现了'cat'
。我在这里错过了什么吗?
的正则表达式与替代的图案(由|
分隔)不扫描第一替换整个字符串,那么第二个。
相反,每个替代被认为是在输入字符串每个位置。因此,在位置0,既不eagle
也不cat
比赛,但在第4位,cat
比赛,即使eagle
是第一次尝试。
因此,cat
被返回作为匹配;其余的字符串不再需要考虑。
当均为模式在相同位置将匹配时,备选排序很重要。所以cat|cats
将返回cat
,始终,即使在输入字符串字后s
:
>>> import re
>>> re.search('cat|cats', 'Like herding cats.').group()
'cat'
>>> re.search('cats|cat', 'Like herding cats.').group()
'cats'
谢谢!那很完美! – elephant
我猜@martijn回答得非常好你的问题,不过,我想指出,你可以使用negative lookahead确保cat
从不其次eagle
,但是,如果cat
来eagle
后,将被匹配:
re.search('eagle|(?!.*eagle)cat', 'The cat is an animal. The eagle is bird.').group()
匹配eagle
如果cat
来后eagle
re.search('eagle|(?!.*eagle)cat', 'The cat is an animal. The eagle is bird, cat is a feline.').group()
将匹配eagle
和第二cat
。
演示:
为什么会是这样?字符串* first *中有一个匹配的'cat'。 –
这会改善你的问题,如果你想编辑它来解释你认为文档中所说的交替意味着什么。 –
我不确定你是否已经找到你需要的东西,但是,你可能想看看前瞻和后视 - http://www.regular-expressions.info/lookaround.html –