python 正则表达式 - 如何用列表中的项目替换多个捕获组

标签 python regex loops

关于正则表达式有很多答案,但没有一个能满足我循环多个匹配项并用列表中的连续项目替换捕获的需要。

我已经搜索过官方文档,但说实话,一些解释和示例对于我来说太高级和复杂,无法理解。到目前为止,我已经弄清楚了如何捕获多个组并命名它们,但我仍然不知道如何在每个组中插入不同的列表项。

<小时/>

伪代码示例...

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/

相关文章:

python - 使用 numpy 计算平均值?

Python:使用 NLTK 时的 "HVZ"标记

python - Python 中的概率模拟

mysql - LIKE '[charlist]%' 语法在 MySQL 中不起作用 (phpMyAdmin)

c - fgets 的循环退出条件不起作用

arrays - 在awk中,当遇到新字符串时如何增加数组索引?

python - 如何使用 boost 元组返回两个 vector

regex - 正则表达式从常用短语中提取单个单词

Javascript 正则表达式在 Edge 中失败,但在所有其他浏览器中工作

c++ - 确定平方根是否为整数