Python 替换两个特定字符之间出现的所有字符
我试图替换两个已知字符(Python 替换两个特定字符之间出现的所有字符,python,regex,Python,Regex,我试图替换两个已知字符(§)之间的所有逗号 我的测试字符串:”§Rd,Vasai-East,Thane§“ 预期输出:”§Rd;瓦赛-东;Thane§’ 我使用以下方法成功删除了一个事件: re.sub(r'(§[^§\r\n]*),([^§\r\n]*§)', r"\1;\2", '§Rd, Vasai - East, Thane§') 但这返回:§Rd,Vasai-East;Thane§我们可以使用re.sub以及用分号替换逗号的回调函数来处理此问题: def repl(m):
§
)之间的所有逗号
我的测试字符串:”§Rd,Vasai-East,Thane§“
预期输出:”§Rd;瓦赛-东;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!
这里的想法是匹配以§
开头和结尾的每个字符串,然后有选择地对该字符串进行另一次替换,以分号替换逗号。我假设,§
总是有一个打开和关闭,或者如果没有,您会同意最后的§
可能是悬挂的。这个表达式
(?<=^§|,)[^,§\r\n]*(?=§$|,)
输出
如果您希望探索/简化/修改该表达式,它已被删除 在的右上面板上进行了说明 . 如果你愿意,你可以 也可以观看,它将如何匹配 对照一些样本输入
成功了!是的,我总是有一个开始和一个结束
§
。
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§