理解python正则表达式

Mel*_*lon 1 python regex

我们假设我有以下字符串:

out = "someUndefinedGarbageVALUE: 12 34 23 00possiblySomeOtherGarbage"
Run Code Online (Sandbox Code Playgroud)

现在我要解析"12 34 23 00"值.在这种情况下,我执行以下操作:

regex = re.compile('VALUE: (\d\d\s?)*')
matches = regex.findall(out)
Run Code Online (Sandbox Code Playgroud)

但是在这种情况下,我只会得到:

00
Run Code Online (Sandbox Code Playgroud)

当我升级正则表达式时:

regex = re.compile('VALUE: ((\d\d\s?)*)')
Run Code Online (Sandbox Code Playgroud)

我会得到:

12 34 23 00, 00
Run Code Online (Sandbox Code Playgroud)

我的问题:

1)使用http://regexpal.com/我看到第一个表达式很好用.试试自己:

VALUE: (\d\d\s?)*
Run Code Online (Sandbox Code Playgroud)

反对

garbageVALUE: 05 03 04garbage
Run Code Online (Sandbox Code Playgroud)

使用Python它是不同的.我的推理在哪里错了?

2)为什么第二个表达式恰好捕获了两个组?它应该只捕获一个

12 34 23 00
Run Code Online (Sandbox Code Playgroud)

或所有可能的变化?

12, 12\s, 12\s34 ...
Run Code Online (Sandbox Code Playgroud)

我知道这是一个贪婪的搜索,但为什么两个群体被捕?

Ara*_*Fey 6

差异是由re.findall.来自文档:

如果模式中存在一个或多个组,则返回组列表

这就解释了为什么你会得到00:这就是小组(\d\d\s?)最后的匹配.

和:

如果模式有多个组,这将是一个元组列表

((\d\d\s?)*)包含两个组,所以findall返回('12 34 23 00', '00').


你可以finditer改用.

>>> print [match.group() for match in re.finditer('VALUE: (\d\d\s?)*', out)]
['VALUE: 12 34 23 00']
Run Code Online (Sandbox Code Playgroud)