正则表达式组捕获多个匹配

时间:2011-04-08 16:55:55

标签: python regex

快速正则表达问题。
我试图在python中捕获捕获组的多个实例(不要认为它是特定于python的),但后续捕获似乎覆盖了之前的捕获。

在这个过于简化的例子中,我基本上试图分割一个字符串:

x = 'abcdef'
r = re.compile('(\w){6}')
m = r.match(x)
m.groups()     # = ('f',) ?!?
我想获得('a', 'b', 'c', 'd', 'e', 'f'),但由于正则表达式会覆盖后续捕获,因此我得到('f',)

这是正则表达式的表现吗?有没有办法做我想做的事情,而不必重复六次语法?

提前致谢!
安德鲁

4 个答案:

答案 0 :(得分:14)

我担心你不能使用群组。每个组只能匹配一次,我相信所有的正则表达式都是这样的。一种可能的解决方案是尝试使用findall()或类似的。

r=re.compile(r'\w')
r.findall(x)
# 'a', 'b', 'c', 'd', 'e', 'f'

答案 1 :(得分:4)

The regex module can do this.

> m = regex.match('(\w){6}', "abcdef")
> m.captures(1)
['a', 'b', 'c', 'd', 'e', 'f']

Also works with named captures:

> m = regex.match('(?P<letter>)\w)', "abcdef")
> m.capturesdict()
{'letter': ['a', 'b', 'c', 'd', 'e', 'f']}

The regex module is expected to replace the 're' module - it is a drop-in replacement that acts identically, except it has many more features and capabilities.

答案 2 :(得分:2)

要查找给定字符串中的所有匹配项,请使用re.findall(regex, string)。此外,如果您想获取此处的每个字母,您的正则表达式应为'(\w){1}''(\w)'

请参阅:

r = re.compile('(\w)')
l = re.findall(r, x)

l == ['a', 'b', 'c', 'd', 'e', 'f']

答案 3 :(得分:1)

我想你的问题是对你的需求的简化陈述。

然后,我举了一个更复杂的例子:

import re

pat = re.compile('[UI][bd][ae]')

ch = 'UbaUdeIbaIbeIdaIdeUdeUdaUdeUbeIda'

print [mat.group() for mat in pat.finditer(ch)]

结果

['Uba', 'Ude', 'Iba', 'Ibe', 'Ida', 'Ide', 'Ude', 'Uda', 'Ude', 'Ube', 'Ida']
相关问题