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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With