了解条件正则表达式 python 中的其他路径如何工作

Understanding how else path in conditional regex python works

我试图理解简单的正则表达式:([+]{1})(?(1)\d{3}|\d{2})

我(很可能是错误的)对上面正则表达式的理解是:如果有一个“+”那么它后面应该直接跟三个数字,否则(如果没有加号)它应该寻找两个数字.

我的两个测试语句是:

1: "This is a +333 test." 
2: "This is a 22 test."

参见:https://regex101.com/r/oJepMi/1/

正则表达式在 1: "+333" 中找到,但在句子 2: 中找不到 "22"。

https://docs.python.org/3/library/re.html 提及:

(?(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."

看似轻松的任务,我却费力地去理解。

有人可以解释一下 else 路径概念如何适用于 python 吗?

致以最诚挚的问候,非常感谢 乔瓦尼

只有当组是可选的或交替的一部分时,使用这种条件才有意义,因此实际上可能不匹配它。

将您的正则表达式更改为 ([+]{1})?(?(1)\d{3}|\d{2}) 以使其正常工作。

请注意,这仍然会匹配 +22 中的 22。你必须添加一个否定的前瞻来检查 + 这不是故意的,例如([+]{1})?(?(1)\d{3}|(?<!)\d{2}) 或更简单的 \+\d{3}|(?<!\+)\d{2}