Skip to main content
 首页 » 编程设计

python之正则表达式字符串替换 : omit comma if backref is empty

2024年10月24日23me-sa

我想使用一个匹配和替换的正则表达式 + 反向引用表达式

text = 'a,b,c' 和 text = 'a,b,c,item_1'

text = '' 与 text = 'item_1' 和

text = 'a' 和 text = 'a,item_1'。

  1. 我通常对使用 sed 和 python regex 的解决方案感兴趣.

  2. 特别是,我正在寻找与 lineinfile 一起使用的解决方案Ansible 的模块(Python)。

这是我目前所拥有的(在 Ansible 中):

regexp:   "^(text[ ]*=[ ]*')([^']*)(')" 
backrefs: yes 
line:     '\1item_1,\2\3' 

编辑:如果可能,regex + backref-ex 对应该忽略已经存在的 item_1,即“替换”

text = 'item_1' 与 text = 'item_1' 和

text = 'a,item_1' 和 text = 'a,item_1' 和

text = 'a,d,x' 和 text = 'a,item_1,x' 等

请您参考如下方法:

这在 sed 中很难做到(在 awk 中可能),因为 sed 中没有替换回调功能。

以下回调方法应该在 python 中工作:

import re 
reg = re.compile(r"(\btext *= *)'([^']*)'") 
 
def repl(m): 
    if len(m.group(2)) == 0: 
        return m.group(1) + "'d'"; 
    else: 
        return m.group(1) + "'" + m.group(2) + ",d'" 
 
 
print(reg.sub(repl, r"text = 'a,b,c'")) 
print(reg.sub(repl, r"text = ''")) 
print(reg.sub(repl, r"text = 'a'")) 

输出:

text = 'a,b,c,d' 
text = 'd' 
text = 'a,d' 

Code Demo