关于正则表达式有很多答案,但没有一个能满足我循环多个匹配项并用列表中的连续项目替换捕获的需要。
我已经搜索过官方文档,但说实话,一些解释和示例对于我来说太高级和复杂,无法理解。到目前为止,我已经弄清楚了如何捕获多个组并命名它们,但我仍然不知道如何在每个组中插入不同的列表项。
<小时/>伪代码示例...
for first_match group:
insert list_item 1
for second_match group:
insert list_item 2
for third_match group :
insert list_item 3
<小时/>
简化的代码示例(我的真实脚本有十几个或更多匹配项)
字符串:
"Substitute a **list_item** here, Substitute a **list_item** here, Substitute a **list_item** here"
正则表达式:
\w.*(?P<first_match>list_item)\W.*\W.*(?P<second_match>list_item)\W.*\W.*(?P<third_match>list_item)
列表
["first_item", "second_item", "third_item"]
我希望实现的目标如下:
"Substitute a **first_item** here, Substitute a **second_item** here, Substitute a **third_item** here"
<小时/>
我也可以通过未命名的组来实现这一点,但命名可以提高可读性。
最佳答案
这可以使用 start() and end() functions 轻松实现.
import re
string= "Substitute a **list_item** here, Substitute a **list_item** here, Substitute a **list_item** here"
pattern= r'\w.*(?P<first_match>list_item)\W.*\W.*(?P<second_match>list_item)\W.*\W.*(?P<third_match>list_item)'
list= ["first_item", "second_item", "third_item"]
result= ''
i= 0
last_match= 0
match= re.match(pattern, string)
for count in xrange(len(match.groups())): # for each group...
result+= string[last_match:match.start(i+1)] # add all text up to the start of the group
result+= list[i] # add the next list item
last_match= match.end(i+1)
i+= 1
result+= string[last_match:] # finally, add all text after the last group
print result
关于python 正则表达式 - 如何用列表中的项目替换多个捕获组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27451797/