我试图替换两个已知字符之间的所有逗号(§
我的测试字符串:'§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§

最佳答案

我们可以使用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!

这里的想法是匹配以§开头和结尾的每个字符串,然后有选择地对该字符串执行另一个替换,以分号替换逗号。我假设§将始终有一个打开和关闭,或者如果没有,您将可以与最后的§可能是悬空。

关于python - 替换两个特定字符之间所有出现的字符,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57838472/

10-12 17:56
查看更多