*排错翻译 - Python字符串替换: How do I replace everything between two strings without replacing the strings?
原创连接:
问题:
Python:如何将两字符串之间的内容替换掉?
I have this string(问题源码):
str = '''
// DO NOT REPLACE ME //
Anything might be here. Numbers letters, symbols, and other strings.
// DO NOT REPLACE ME EITHER //
'''
I want to replace whatever is between those two lines, but I do not want to replace those strings. How do I do this?
翻译:我想替换两字符串之间的内容,但不替换字符。如何实现?
解答:
解答源码:
>>> s = '''
// DO NOT REPLACE ME //
Anything might be here. Numbers letters, symbols, and other strings.
// DO NOT REPLACE ME EITHER //
'''
>>> print(s) // DO NOT REPLACE ME //
Anything might be here. Numbers letters, symbols, and other strings.
// DO NOT REPLACE ME EITHER //
>>> import re
>>> start = '// DO NOT REPLACE ME //'
>>> end = '// DO NOT REPLACE ME EITHER //'
>>> replacement = 'stuff'
>>> match = re.match(r'(.+%s\s*).+?(\s*%s.+)' % (start, end), s, re.DOTALL)
>>> match.groups()
('\n // DO NOT REPLACE ME //\n ', '\n // DO NOT REPLACE ME EITHER //\n ')
>>> new = match.group(1) + replacement + match.group(2)
>>> print(new) // DO NOT REPLACE ME //
stuff
// DO NOT REPLACE ME EITHER //
解答原文:May cause problems if start
or end
contain special regex characters. In this case they don't.
翻译:如果start
或 end 值中包含正值表达式的字符,在执行时可能会出问题.