Home > regular expressions > How to replace a substring using regex in Python

How to replace a substring using regex in Python

The problem: You match a string with your regex, but you need to replace just a portion of it. How could we replace it?
The trick is simple, put the text you want to replace within “()” which means “group” in regex language. If the regex worked, you could replace just that portion by using Python match information, like in this example:

#the first group contains the expression we want to replace
pat = "word1\s(.*)\sword2"
test = "word1 will never be a word2"
repl = "replace"

import re
m = re.search(pat,test)

if m and m.groups() > 0:
  line = test[0:m.start(1)] + repl + test[m.end(1):len(test)]
  print line
else:
  print "the pattern didn't capture any text"

This will print: ‘word1 will never be a word2

The group to be replaced could be located in any position of the string.

  1. ??????
    August 7th, 2010 at 19:52 | #1

    Hi guys, tried loading this blog through Google RSS reader and got a strange error message, any ideas what could be the issue?

  2. c p
    August 23rd, 2010 at 20:25 | #2

    Keep posting stuff like this i really like it

  3. admin
    August 25th, 2010 at 03:05 | #3

    Hi, just tried RSS in Google reader and worked as a charmed. Are you trying http://adrian.org.ar/feed ?

  4. admin
    August 25th, 2010 at 03:09 | #4

    thank you!

  5. Serial
    September 24th, 2010 at 18:23 | #5

    Respect to the author of original work. I am want to say thanks for interesting post, and thanks to google for perfect blog search.

  6. sfsdsgdf
    September 24th, 2010 at 19:59 | #6

    first post

  7. f l
    October 5th, 2010 at 12:23 | #7

    this post is very usefull thx!

  1. No trackbacks yet.