我需要使用如下所示的python替换所有出现的点,但仅当点在括号中时才用其他东西(例如分号)替换:
输入:"Hello (This . will be replaced, this one. too)."
输出:"Hello (This ; will be replaced, this one; too)."
答案 0 :(得分:1)
假设括号是平衡的而不是嵌套的,这是re.split
的想法。
>>> import re
>>>
>>> s = 'Hello (This . will be replaced, this one. too). This ... not but this (.).'
>>> ''.join(m.replace('.', ';') if m.startswith('(') else m
...: for m in re.split('(\([^)]+\))', s))
...:
'Hello (This ; will be replaced, this one; too). This ... not but this (;).'
这里的主要技巧是将正则表达式\([^)]+\)
与另一对()
进行包装,以保持拆分匹配。
答案 1 :(得分:0)
这不是最优雅的方法,但是应该可以。
def sanitize(string):
string = string.split("(",1)
string0 = str(string[0])+"("
string1 = str(string[1]).split(")",1)
ending = str(")"+string1[1])
middle = str(string1[0])
# replace second "" with character you'd like to replace with
# I.E. middle.replace(".","!")
middle = middle.replace(".","").replace(";","")
stringBackTogether = string0+middle+ending
return stringBackTogether
a = sanitize("Hello (This . will be replaced, this one. too).")
print(a)
答案 2 :(得分:0)
圈起字符串中的字符,跟踪开括号和闭括号的数量,只有在开括号大于闭括号的情况下才进行替换。
std::regex