替换两个特定字符之间所有出现的字符

时间:2019-09-08 01:01:55

标签: python regex

我正在尝试替换两个已知字符(§)之间的所有逗号

我的测试字符串:'§Rd, Vasai - East, Thane§'

预期输出:'§Rd; Vasai - East; Thane§'

我设法使用以下方法删除了一次事件:

re.sub(r'(§[^§\r\n]*),([^§\r\n]*§)', r"\1;\2", '§Rd, Vasai - East, Thane§') 

但这返回:§Rd, Vasai - East; Thane§

2 个答案:

答案 0 :(得分:5)

我们可以使用re.sub以及一个用分号替换逗号的回调函数来处理此问题:

def repl(m):
    str = m.group(0)
    return str.replace(",", ";")

inp = "Hello World blah, blah, §Rd, Vasai - East, Thane§ also Goodbye, world!"
print(inp)
print re.sub('§.*?§', repl, inp)

此打印:

Hello World blah, blah, §Rd, Vasai - East, Thane§ also Goodbye, world!
Hello World blah, blah, §Rd; Vasai - East; Thane§ also Goodbye, world!

这里的想法是匹配以§开头和结尾的每个字符串,然后有选择地对该字符串进行另一个替换,以用分号替换逗号。我假设§总是会打开和关闭,或者如果没有,那么最后的§可能会晃来晃去。

答案 1 :(得分:0)

此表达式

(?<=^§|,)[^,§\r\n]*(?=§$|,)

re.findall一起使用也可能会起作用:

import re

matches = re.findall(r'(?<=^§|,)[^,§\r\n]*(?=§$|,)', "§Rd, Vasai - East, Thane§")
length = len(matches)
output = '§'
for i in range(length):
    if i == length - 1:
        output += str(matches[i]) + '§'
    else:   
        output += str(matches[i]) + ';'

print(output)

输出

§Rd; Vasai - East; Thane§

  

如果您想探索/简化/修改表达式,可以   在右上角的面板上进行了说明   regex101.com。如果您愿意,   也可以在this link中观看它的匹配方式   针对一些样本输入。