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

Schif Schaf schifschaf at gmail.com
Sun Feb 7 05:49:06 CET 2010


Hi,

I've got some text that looks like this:


    Lorem [ipsum] dolor sit amet, consectetur
    adipisicing elit, sed do eiusmod tempor
    incididunt ut [labore] et [dolore] magna aliqua.

and I want to make it look like this:


    Lorem {ipsum} dolor sit amet, consectetur
    adipisicing elit, sed do eiusmod tempor
    incididunt ut {labore} et {dolore} magna aliqua.

(brackets replaced by braces). I can do that with Perl pretty easily:

~~~~
for (<>) {
    s/\[(.+?)\]/\{$1\}/g;
    print;
}
~~~~

but am not able to figure out how to do it with Python. I start out
trying something like:

~~~~
import re, sys
withbracks = re.compile(r'\[(.+?)\]')
for line in sys.stdin:
    mat = withbracks.search(line)
    if mat:
        # Well, this line has at least one.
        # Should be able to use withbracks.sub()
        # and mat.group() maybe ... ?
        line = withbracks.sub('{' + mat.group(0) + '}', line)
        # No, that's not working right.

    sys.stdout.write(line)
~~~~

but then am not sure where to go with that.

How would you do it?

Thanks.



More information about the Python-list mailing list