Skip to main content
 首页 » 编程设计

python之用正则表达式插入字符

2025年05月04日31mfryf

我有一个字符串'(abc)def(abc)',我想将它变成'(a|b|c)def(a|b|c)'。我可以通过以下方式做到这一点:

    word = '(abc)def(abc)' 
    pattern = '' 
    while index < len(word): 
        if word[index] == '(': 
            pattern += word[index] 
            index += 1 
            while word[index+1] != ')': 
                pattern += word[index]+'|' 
                index += 1 
            pattern += word[index] 
        else: 
            pattern += word[index] 
        index += 1 
     print pattern 

但是我想用正则表达式让它更短。你能告诉我如何插入字符'|'吗通过正则表达式仅在括号内的字符之间?

请您参考如下方法:

怎么样

>>> import re 
>>> re.sub(r'(?<=[a-zA-Z])(?=[a-zA-Z-][^)(]*\))', '|', '(abc)def(abc)') 
'(a|b|c)def(a|b|c)' 
  • (?<=[a-zA-Z])正面看后面。确保要插入的位置前面有字母。

  • (?=[a-zA-Z-][^)(]*\))积极展望 future 。确保位置后跟字母

    • [^)(]*\)确保 () 中的字母表

    • [^)(]*匹配 ( 以外的任何内容或 )

    • \)确保 除 ( 之外的任何内容或 ) 之后是 )

      这部分很关键,因为它与 def 部分不匹配自 def不以 ) 结尾