2011-05-16 68 views
42

如果我做findall(r'regex(with)capturing.goes.here'),如何访问捕获的组? 我知道我可以通过finditer来完成,但我不想迭代。用findall捕获组?

回答

39

findall刚刚返回拍摄组:

>>> re.findall('abc(de)fg(123)', 'abcdefg123 and again abcdefg123') 
[('de', '123'), ('de', '123')] 

相关文档摘录:

返回字符串中 模式的所有非重叠匹配项,作为 字符串的列表。扫描字符串 从左到右依次为 ,找到的顺序返回。如果 模式中有一个或多个组存在,则返回组列表;如果 模式具有多个组,则此 将成为元组列表。空 匹配包含在结果 中,除非它们触及另一个匹配的起始 。

15

自由使用组。本场比赛将返回为组元组的列表:

>>> re.findall('(1(23))45', '12345') 
[('123', '23')] 

如果你想在全场比赛被收录,只是封装一组在整个正则表达式:

>>> re.findall('(1(23)45)', '12345') 
[('12345', '23')] 
1

几种方法是可行的:

>>> import re 
>>> r = re.compile(r"'(\d+)'") 
>>> result = r.findall("'1', '2', '345'") 
>>> result 
['1', '2', '345'] 
>>> result[0] 
'1' 
>>> for item in result: 
...  print(item) 
... 
1 
2 
345 
>>> 
+1

我觉得他问内的正则表达式组为“(1组)。(第2组)” – bluepnume 2011-05-16 13:55:35

+0

@bluepnume:也许吧,但他的问题并不清楚。他的例子只有一个捕获组。 – 2011-05-16 13:57:39

0
import re 
string = 'Perotto, Pier Giorgio' 
names = re.findall(r''' 
       (?P<first>[-\w ]+),\s #first name 
       (?P<last> [-\w ]+) #last name 
       ''',string, re.X|re.M) 

print(names) 

回报

[('Perotto', 'Pier Giorgio')] 

re.M才有意义,如果你的字符串是多。还需要在正则VERBOSE(等于re.X)模式,我已经写了,因为它是用'''