[英]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.