1

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.

4
  • 1
    Is the string to be replaced always the same? In that case, you don't need a regex. Commented Aug 4, 2013 at 13:40
  • if these are url's as they appear to be, the & has special meaning so your statement that "the & and the $ could be any symbol" feels wrong. Commented Aug 4, 2013 at 13:43
  • the string to be replaced is not the same always :( Commented Aug 4, 2013 at 13:44
  • I would want it to always replace the value of mytag - if this makes sense. i.e mytag will always be present in the string. Commented Aug 4, 2013 at 13:47

3 Answers 3

1

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'
Sign up to request clarification or add additional context in comments.

1 Comment

Just posted an update - sorry, the string to be replaced is always not the same. Sorry for not being clear the first time around.
1

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$'

3 Comments

@Ashwini: This is awesome. Could you please explain why you use \1?
@JohnJ \1 represents the first matching group i.e 'mytag='.
@AshwiniChaudhary: Thank you very much for your explanation. Accepted your answer! Was breaking my head over this for a couple of hours. Thanks again.
0
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.