python 正则表达式 if|else 没有像宣传的那样工作?

python regex if|else not working as advertised?

我正在尝试自学 if|else 模式匹配在 python 中的工作原理,因此从 documentation 创建了以下测试。据我所知,它在文档中不起作用,但我学会了假设我错过了某个地方的关键步骤。

在此测试用例中,第三项 应该 失败,因为它缺少结束符 '>'。

In [1]: import re, sys
In [2]: regex = re.compile('(<)?(\w+@\w+(?:\.\w+)+)(?(1)>|$)')
In [3]: cases  = ['<user@host.com>', 'user@host.com', '<user@host.com', 'user@host.com>']

In [4]: [ re.search(regex, _) and ("match:", _) or ("fail:", _) for _ in cases ]
Out[4]:
[('match:', '<user@host.com>'),
 ('match:', 'user@host.com'),
 ('match:', '<user@host.com'),
 ('fail:', 'user@host.com>')]

In [5]: sys.version
Out[5]: '3.6.5 |Anaconda custom (64-bit)| (default, Apr 26 2018, 08:42:37) \n[GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)]'

相关:

(?(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. no-pattern is optional and can be omitted. For example, (<)?(\w+@\w+(?:\.\w+)+)(?(1)>|$) is a poor email matching pattern, which will match with '<user@host.com>' as well as 'user@host.com', but not with '<user@host.com' nor 'user@host.com>'.

所以我的问题是,我错过了哪一步?尝试了不同的 python 版本和 hosts/os.

您正在使用 search,询问字符串 是否包含 匹配您的正则表达式,而不是询问它是否 一场比赛。 <user@host.com 包含一个匹配项,特别是 user@host.com.

使用 fullmatch 而不是 search