繁体   English   中英

python使用正则表达式和组,如何获取所有匹配项?

[英]python using regex with groups, how do you get all the matches?

我正在使用python re来匹配组。 当我将其与+一起使用时,我似乎“失去”了第一个匹配项。 result.group(1)仅显示最后一个。 我确实在result.group(0)中看到了它们,但这并没有真正的帮助。 有没有办法查看group(1)匹配的所有匹配项?

在下面的示例中,我希望group(1)打印%one%two%three,而不是%three

(group(0)将不起作用,因为在现实世界中,最初的比赛之后是东西)

import sys
import re

line = '%one %two %three'
re_rule = re.compile("\s*(%\w+\s*)+")

result = re_rule.match(line)
if result:
    print("DBG:", result.group(1))
    print("DBG:", result.group(0))
import re

line = '%one %two %three'
re_rule = re.compile("%(\w+)")
f
result = re_rule.findall(line)

print(result)

输出为:

['one', 'two', 'three']

这里的技巧是使用findall https://docs.python.org/3/library/re.html#re.regex.findall

re引擎仅保留重复捕获组的最后一次迭代,但是我们可以通过将重复的非捕获组封装在一个捕获组中来规避这种行为

re_rule = re.compile("((?:%\w+\s*)+)")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM