nedla2004 nedla2004 - 15 days ago 5
Python Question

Regex String Slicing

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
. If it matched
abc Hello, World cba
, that should change to
efg Hello, World
.

Answer

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.

Comments