Python:如何在不替换字符串的情况下替换两个字符串之间的所有内容?

时间:2016-12-27 00:13:13

标签: python python-2.7

我有这个字符串

str = '''
      // DO NOT REPLACE ME //
      Anything might be here. Numbers letters, symbols, and other strings.
      // DO NOT REPLACE ME EITHER //
      '''

我想替换这两行之间的任何内容,但我不想替换这些字符串。我该怎么做?

2 个答案:

答案 0 :(得分:3)

>>> 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 //

如果startend包含特殊的正则表达式字符,可能会导致问题。在这种情况下,他们不会。

答案 1 :(得分:0)

start = s.find('// DO NOT REPLACE ME //') + len('// DO NOT REPLACE ME //')
end = s.find('// DO NOT REPLACE ME EITHER //')
new_string = s[:start] + replacement + s[end:]

我希望它有所帮助