无法调试 Python 正则表达式

Cannot debug a Python regex

我正在尝试调试以下 Python 正则表达式

<meta name="Author" content=".*(?P<uid>([a-zA-Z]*))@abc\.com.*

我使用以下字符串作为示例:

<meta name="Author" content="qwerty(qwerty@abc.com)#comments=release candidate for AA 1.1">

你能解释一下为什么下面的代码找不到组 "uid":

regex = re.compile(r'<meta name="Author" content=".*(?P<uid>([a-zA-Z]*))@abc\.com')
a = '<meta name="Author" content="qwerty(qwerty@abc.com)#comments=release candidate for AA 1.1">'
q = regex.search(a)
if q:
    print(q.group('uid'))

我都做了一个DFA,还是不明白为什么找不到群。

你只需要这个:

regex = re.compile(r'(?P<uid>([a-zA-Z]*))@abc\.com')
a = '<meta name="Author" content="qwerty(qwerty@abc.com)#comments=release candidate for AA 1.1">'
q = regex.search(a)
if q:
    print(q.group('uid'))

Returns: qwerty

(正如@Błotosmętek 所解释的那样,由于 .* 贪婪 ,您的解决方案不起作用)

问题是由 .* 模式的贪婪引起的。在 content=".*(?P<uid>([a-zA-Z]*))@abc\.com 中,直到 @abc 的所有内容都与 .* 匹配,留下空字符串以供您的组匹配。上面 Peter Prescott 的解决方案是合理的,但如果您坚持使用更长的正则表达式,请使用:

r'<meta name="Author" content=".*\((?P<uid>[a-zA-Z]*)@abc\.com'

以便 .*( 处停止匹配。