Help with regex search-and-replace (Perl to Python)

Schif Schaf schifschaf at
Sun Feb 7 06:45:39 CET 2010

On Feb 7, 12:19 am, "Alf P. Steinbach" <al... at> wrote:

> I haven't used regexps in Python before, but what I did was (1) look in the
> documentation,

Hm. I checked in the repl, running `import re; help(re)` and the docs
on the `sub()` method didn't say anything about using back-refs in the
replacement string. Neat feature though.

> (2) check that it worked.
> <code>
> import re
> text = (
>      "Lorem [ipsum] dolor sit amet, consectetur",
>      "adipisicing elit, sed do eiusmod tempor",
>      "incididunt ut [labore] et [dolore] magna aliqua."
>      )
> withbracks = re.compile( r'\[(.+?)\]' )
> for line in text:
>      print( re.sub( withbracks, r'{\1}', line) )
> </code>

Seems like there's magic happening here. There's the `withbracks`
regex that applies itself to `line`. But then when `re.sub()` does the
replacement operation, it appears to consult the `withbracks` regex on
the most recent match it just had.


More information about the Python-list mailing list