I am using Python flavor if regex, and I need to slice a string while replacing text. The regex I am using to match my needed string is this,
abc .+ cba
abc Hello, World cba
efg Hello, World
Use a capturing group:
>>> s = "here is some stuff abc Hello, World cba here is some more stuff" >>> import re >>> re.sub(r'abc (.+) cba', r'efg \1',s) 'here is some stuff efg Hello, World here is some more stuff' >>>
Note: the replacement string accepts a backreference.