Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How do I replace everything between two strings without replacing the strings?

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?

like image 594
Username Avatar asked May 23 '26 02:05

Username


1 Answers

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

like image 63
Alex Hall Avatar answered May 25 '26 16:05

Alex Hall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!