StackOverFlow排錯翻譯 - Python字符串替換: How do I replace everything between two strings without replacing the strings?html
原創鏈接:python
Python字符串替換this
問題:翻譯
Python:如何將兩字符串之間的內容替換掉?code
I have this string(問題源碼):htm
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?ci
翻譯:我想替換兩字符串之間的內容,但不替換字符。如何實現?字符串
解答:get
解答源碼:源碼
>>> 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 值中包含正值表達式的字符,在執行時可能會出問題.