[英]Im trying to figure out a regex with using (?(ID/NAME).......)
>>> p = re.compile(r'(((x)|y)(?(2)y|x))+')
>>> p.search('yxxyyx')
<_sre.SRE_Match object; span=(2, 4), match='xy'>
My questions: why it matches only 'xy'?我的问题:为什么它只匹配“xy”? and does \\2 always refer to "x" within the group (.......)+??
并且 \\2 是否总是指组中的“x” (.......)+??
edited: Thank you for all your answers!编辑:感谢您的所有回答! I found a helpful website to make regex visualize.
我找到了一个有用的网站来使正则表达式可视化。
Questions:问题:
Answer Question 2 first:先回答问题2:
In this regex, you are using:在此正则表达式中,您使用的是:
(?(id/name)yes-pattern|no-pattern)
Will try to match with yes-pattern if the group with given id or name exists, and with no-pattern if it doesn't.
如果具有给定 id 或名称的组存在,将尝试与 yes-pattern 匹配,如果不存在则与 no-pattern 匹配。 no-pattern is optional and can be omitted.
no-pattern 是可选的,可以省略。 For example, (<)?(\\w+@\\w+(?:.\\w+)+)(?(1)>) is a poor email matching pattern, which will match with '' as well as 'user@host.com', but not with '
例如, (<)?(\\w+@\\w+(?:.\\w+)+)(?(1)>) 是一个糟糕的电子邮件匹配模式,它将与 '' 以及 'user@host 匹配。 com',但不带 '
In the regex given ((x)|y)
, there is only one group before the question (?(2)y|x))+
that asks whether the second group has matched.在给定的正则表达式
((x)|y)
,在问题(?(2)y|x))+
之前只有一组询问第二组是否匹配。 Since there is only one group the conditional will always be false, and thus will always try to match x
由于只有一组,因此条件将始终为假,因此将始终尝试匹配
x
Answer Question 1:回答问题 1:
Yes, since there is only one group, the conditional will always match x
, and the entire regex only match xyx
是的,因为只有一组,条件总是匹配
x
,整个正则表达式只匹配xyx
我发现这个网站是学习和测试不同正则表达式模式的好资源。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.