这里有很多关于正则表达式的答案,但是没有一个符合我的需求:循环匹配多个结果并用列表中连续的项替换捕获内容。我查看了官方文档,但说实话,其中一些解释和示例对我来说太高级和复杂了。到目前为止,我已经学会了如何捕获多个组并给它们命名,但我卡在了如何插入不同的列表项的问题上。
伪代码示例...
列表
伪代码示例...
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"]
What I'm hoping to achieve looks like this:
"Substitute a **first_item** here, Substitute a **second_item** here, Substitute a **third_item** here"
我也可以使用未命名的组来实现这一点,但是使用命名可以使内容更加易读。
(?<Before_item1>\w.)(?<Before_item2>\W.\W.)(?<Before_item3>\W.\W.*)
替换:$+{Before_item1}$list[1]$+{Before_item2}$list[2]$+{Before_item3}$list[3]
- user557597