KIDJourney KIDJourney - 1 year ago 65
Python Question

python re . replace string with what i search

For example . I have a string :

The struct-of-application and struct-of-world

and i write a simple regex
and try to use re.sub

In [10]: p.sub('struct','The struct-of-application and struct-of-world')
Out[10]: 'The struct and struct'

It seems i can't use what i matched to replace what i matched, let alone edit the matched content.

How can i replace with the edited matched content (reverse, for example) and get:

The [application_of_struct](http://application_of_struct) and [world-of-struct](http://world-of-struct)

it will replace the matched with certain string. How can i replace with matched content ?

Answer Source

Use a function for the replacement

s = 'The struct-of-application and struct-of-world'
p = re.compile('((\w+-)+\w+)')
def replace(match):
    return 'http://{}'.format( 

>>> p.sub(replace, s)

'The http://struct-of-application and http://struct-of-world'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download