【问题标题】:Cannot debug a Python regex [duplicate]无法调试 Python 正则表达式 [重复]
【发布时间】:2020-04-13 14:56:46
【问题描述】:

我正在尝试调试以下 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,但仍然无法理解为什么找不到该组。

【问题讨论】:

  • 您与( 不匹配组 uid 中的预期值?见regex101.com/r/BYRMXD/1
  • 只需删除.* 子模式,它们匹配您需要提取的字符串前后一行的所有文本。

标签: python regex regex-group


【解决方案1】:

你只需要这个:

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'))

返回:qwerty

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

【讨论】:

  • 为什么re.findall没有解决“.*”的贪婪?
  • docs。空匹配仍然是匹配。而findall 只是意味着它在找到匹配项后不会停止。 非空匹配现在可以在之后前一个空匹配开始。
【解决方案2】:

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

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

这样.*( 处停止匹配。

【讨论】:

  • 我明白了,Peter Prescott 提出的解决方案肯定有效。但是为什么 re.findall 找不到组呢?
  • @GrigoriyVolkov - 如果可行,请accept the answer :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-04-22
  • 2016-08-31
  • 2015-10-01
  • 2016-11-16
  • 1970-01-01
  • 1970-01-01
  • 2013-05-19
相关资源
最近更新 更多