JohnJ
JohnJ

Reputation: 7066

regex and replace on string using python

I am rather new to Python Regex (regex in general) and I have been encountering a problem. So, I have a few strings like so:

str1 = r'''hfo/gfbi/mytag=a_17014b_82c'''
str2 = r'''/bkyhi/oiukj/game/?mytag=a_17014b_82c&'''
str3 = r'''lkjsd/image/game/mytag=a_17014b_82c$'''

the & and the $ could be any symbol.

I would like to have a single regex (and replace) which replaces:

mytag=a_17014b_82c

to:

mytag=myvalue

from any of the above 3 strings. Would appreciate any guidance on how I can achieve this.

UPDATE: the string to be replaced is always not the same. So, a_17014b_82c could be anything in reality.

Upvotes: 1

Views: 167

Answers (3)

Sundar R
Sundar R

Reputation: 14735

import re
r = re.compile(r'(mytag=)\w+$')
r.sub(r'\1myvalue', str1)

This is based on @Ashwini's answer, two small changes are we are saying the mytag=a_17014b part should be at the end of input, so that even inputs such as

str1 = r'''/bkyhi/mytag=blah/game/?mytag=a_17014b_82c&'''

will work fine, substituting the last mytag instead of the the first.

Another small change is we are not unnecessarily capturing the \w+, since we aren't using it anyway. This is just for a bit of code clarity.

Upvotes: 0

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251196

Use re.sub:

>>> import re
>>> r = re.compile(r'(mytag=)(\w+)')
>>> r.sub(r'\1myvalue', str1)
'hfo/gfbi/mytag=myvalue'
>>> r.sub(r'\1myvalue', str2)
'/bkyhi/oiukj/game/?mytag=myvalue&'
>>> r.sub(r'\1myvalue', str3)
'lkjsd/image/game/mytag=myvalue$'

Upvotes: 1

keyser
keyser

Reputation: 19209

If the string to be replaced is constant you don't need a regex. Simply use replace:

>>> str1 = r'''hfo/gfbi/mytag=a_17014b_82c'''
>>> str1.replace('a_17014b_82c','myvalue')
'hfo/gfbi/mytag=myvalue'

Upvotes: 1

Related Questions