Skip to main content
 首页 » 编程设计

python之理解 python 正则表达式

2025年05月04日23kevingrace

假设我有以下字符串:

out = "someUndefinedGarbageVALUE: 12 34 23 00possiblySomeOtherGarbage" 

现在我想解析“12 34 23 00”值。在这种情况下,我执行以下操作:

regex = re.compile('VALUE: (\d\d\s?)*') 
matches = regex.findall(out) 

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

00 

当我稍微升级正则表达式时:

regex = re.compile('VALUE: ((\d\d\s?)*)') 

我会得到:

12 34 23 00, 00 

我的问题:

1) 与 http://regexpal.com/我看到第一个表达式效果很好。自己试试:

VALUE: (\d\d\s?)* 

反对

garbageVALUE: 05 03 04garbage 

使用 Python 则不同。我的推理哪里错了?

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

12 34 23 00 

或所有可能的变体?

12, 12\s, 12\s34 ... 

我明白这是一个贪心搜索,但为什么恰好抓到两个组?

请您参考如下方法:

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

If one or more groups are present in the pattern, return a list of groups

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

和:

this will be a list of tuples if the pattern has more than one group

((\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']