2

I want to replace the content of a string using regex in python.

I have tried the following code:

regex=r"(?:ab*)\w+"
text ="absd 2013 abpq ab 123absd"
pattern=re.compile(regex)
print pattern.sub("dummy",text)

I got the output like this:

dummy 2013 dummy dummy 123dummy

But my actual text is still same.

Can I modify the text itself with a regex?

Blckknght
  • 100,903
  • 11
  • 120
  • 169
user2256009
  • 169
  • 1
  • 2
  • 9

2 Answers2

1

In Python, Strings are immutable. So, you cannot change them. What you can do is, replace the old reference to string object with the new string object, like this

text = pattern.sub("dummy", text)

Also, if you are trying to replace all the strings which start with ab, then you might want to use this RegEx,

regex = r"ab.*?\b"
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
1

You need to store the result back into the text as follows:

text = pattern.sub("dummy",text)

sub:

Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl

This "returned string" is not actually the original replaced string. It is a new string that contains the replaced string. Therefore, you need to assign it back to the original string

Now you will the expected modified string:

print test
dummy 2013 dummy dummy 123dummy
sshashank124
  • 31,495
  • 9
  • 67
  • 76