替换匹配组可能重叠的正则表达式匹配组

时间:2016-07-17 17:30:50

标签: python regex string

我在Python工作。我有一个与我的正则表达式匹配的字符串,并且想要替换所有匹配组(最终目标是将每个组包装在HTML范围内)。

我知道有很好的方法可以使用re模块执行此操作但是我不知道我的情况是否可以处理,因为我知道我的一些匹配重叠。

我查看了re模块和字符串模板,但我不认为在这种情况下帮助我。我也尝试过自己实现一个解决方案,但我还没有运气,感觉应该有更好的解决方案。

E.g。假设我有字符串:

"This is my cat her name is Alice" 

我正在使用这种模式:

"This is my cat (her name is (\w+)).

在这种情况下,我应该:

match 0: "This is my cat her name is Alice"
match 1: "her name is Alice"
match 2: "Alice"

我想结束看起来像这样的事情

"This is my cat <span class=\"class1\">is <span class=\"class2\">Alice</span></span>

1 个答案:

答案 0 :(得分:1)

  1. 创建组开始和结束的索引列表。您可以使用.start([group]) and .end([group])函数。 (确保您有一些方法可以区分组开始与组结束。)
  2. 按降序索引对列表进行排序。
  3. 对于列表中的每个索引,如果它是结束索引,请插入</span>;如果是起始索引,则插入<span class="whatever">
  4. 代码:

    match= re.match(p, s)
    indices= sorted([(match.start(index),True) for index,group in enumerate(match.groups(),1)]+ \
                    [(match.end(index),False) for index,group in enumerate(match.groups(),1)], reverse=True)
    for index,is_start in indices:
        if is_start:
            s= s[:index]+'<span class="class1">'+s[index:]
        else:
            s= s[:index]+'</span>'+s[index:]
    print s
    # output: This is my cat <span class="class1">her name is <span class="class1">Alice</span></span>
    
相关问题