如果我做findall(r'regex(with)capturing.goes.here')
,如何访问捕获的组? 我知道我可以通过finditer
来完成,但我不想迭代。用findall捕获组?
42
A
回答
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
>>>
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
)模式,我已经写了,因为它是用'''
相关问题
- 1. 非捕获组内的捕获组
- 2. 捕获组VS未捕获组
- 3. 捕获组
- 4. php捕获组
- 5. 捕获组
- 6. 用grep命名捕获组
- 7. 捕获中包含非捕获组?
- 8. 第二个捕获组未捕获
- 9. BeautifulSoup,findAll findAll后?
- 10. 获取捕捉组
- 11. 可选捕获组
- 12. 捕获组多次
- 13. R中的正则表达式组捕获多个捕获组
- 14. 正则表达式忽略捕获组内的捕获组
- 15. 使用findAll方法Groovy过滤数组
- 16. 使用关联和外键组合findAll
- 17. 使用捕获组在应用re.sub
- 18. preg_match捕捉周期\。在非捕获组
- 19. 并行sed与组捕获
- 20. RewriteCond捕获组不匹配
- 21. Python重复捕获组
- 22. 捕获组不能与NSRegularExpression
- 23. 捕获组+数字为PHP
- 24. Perl命名捕获组
- 25. 捕获正确的组
- 26. Groovy - 多重捕获组
- 27. Python 3,捕获组合键
- 28. 捕获重复命名组
- 29. 重复命名捕获组
- 30. 复杂的元组捕获
我觉得他问内的正则表达式组为“(1组)。(第2组)” – bluepnume 2011-05-16 13:55:35
@bluepnume:也许吧,但他的问题并不清楚。他的例子只有一个捕获组。 – 2011-05-16 13:57:39