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

Shashwat Anand anand.shashwat at gmail.com
Sun Feb 7 10:03:07 CET 2010


Here is one simple solution :
>>> intext = """Lorem [ipsum] dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor  incididunt ut [labore] et [dolore] magna aliqua."""

>>> intext.replace('[', '{').replace(']',
'}')
'Lorem {ipsum} dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor  incididunt ut {labore} et {dolore} magna aliqua.'

*Some people, when confronted with a problem, think "I know, I’ll use
regular expressions." Now they have two problems.* — Jamie
Zawinski<ttp://jwz.livejournal.com>in comp.lang.emacs.


On Sun, Feb 7, 2010 at 11:15 AM, Schif Schaf <schifschaf at gmail.com> wrote:

> On Feb 7, 12:19 am, "Alf P. Steinbach" <al... at start.no> 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.
>
> Thanks.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20100207/0657f8e8/attachment.html>


More information about the Python-list mailing list