Python Regular Expressions: re.sub(regex, replacement, subject)

Benjamin Niemann pink at odahoda.de
Tue Jul 5 13:00:13 EDT 2005


Vibha Tripathi wrote:

> Hi Folks,
> 
> I put a Regular Expression question on this list a
> couple days ago. I would like to rephrase my question
> as below:
> 
> In the Python re.sub(regex, replacement, subject)
> method/function, I need the second argument
> 'replacement' to be another regular expression ( not a
> string) . So when I find a 'certain kind of string' in
> the subject, I can replace it with 'another kind of
> string' ( not a predefined string ). Note that the
> 'replacement' may depend on what exact string is found
> as a result of match with the first argument 'regex'.

Do mean 'backreferences'?

>>> re.sub(r"this(\d+)that", r"that\1this", "this12that foo13bar")
'that12this foo13bar'

Note that the replacement string r"that\1this" is not a regular expression,
it has completely different semantics as described in the docs. (Just
guessing: are you coming from perl? r"xxx" is not a regular expression in
Python, like /xxx/ in perl. It's is just an ordinary string where
backslashes are not interpreted by the parser, e.g. r"\x" == "\\x". Using
r"" when working with the re module is not required but pretty useful,
because re has it's own rules for backslash handling).

For more details see the docs for re.sub():
http://docs.python.org/lib/node114.html

-- 
Benjamin Niemann
Email: pink at odahoda dot de
WWW: http://www.odahoda.de/



More information about the Python-list mailing list