nedla2004 nedla2004 - 1 year ago 118
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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download