如果括号是嵌套的,则不能使用正则表达式。来点split
-fu怎么样?
def replace_outside(string, original, replacement):
level = 0 #the level of nesting - 0 is outside
result = [] #a temp list holding the result
while string:
#split the string until the first '<', save everything before that in
#current and process the rest in the next iteration
splitstr = string.split("<", 1)
if len(splitstr) == 1: current, string = string, ""
else: current, string = tuple(splitstr)
if level == 0:
#we're outside - replace everything in current string
current = current.replace(original, replacement)
else:
#decrease the level by the number of closing brackets in current
level -= current.count(">")
if level == 0:
#everything after the last '>' is outside
inner, outer = current.rsplit(">", 1)
#replace outer and join with inner again
outer = outer.replace(original, replacement)
current = '>'.join([inner, outer])
#append the string to the result list and increase level by one
result.append(current)
level += 1
#return the result list joined by the '>' we split it by
return '<'.join(result)
(如果有任何不匹配的括号,这显然会失败。)