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



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/
.



Relevant Pages

  • Re: Regular expression optimization
    ... position in the replacement array of strings, ... > input string and a MatchEvaluator delegate. ... > The first part required combining the separate Regular Expression strings ...
    (microsoft.public.dotnet.general)
  • Re: Regular expression optimization
    ... string and a MatchEvaluator delegate. ... The first part required combining the separate Regular Expression strings ... The class has a private string array of replacement ...
    (microsoft.public.dotnet.general)
  • Re: Python Regular Expressions: re.sub(regex, replacement, subject)
    ... > In the Python re.sub(regex, replacement, subject) ... > string). ...
    (comp.lang.python)
  • Python Regular Expressions: re.sub(regex, replacement, subject)
    ... I put a Regular Expression question on this list a ... In the Python re.sub(regex, replacement, subject) ... So when I find a 'certain kind of string' in ... Mail has the best spam protection around ...
    (comp.lang.python)
  • Re: Get regular expression
    ... own tree structure. ... Expression compares a string character-by character, ... regular expression solution, which was about as close as one could get to ... the structure of the hierarchy can be inferred by using ...
    (microsoft.public.dotnet.languages.csharp)