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

Alf P. Steinbach alfps at start.no
Sun Feb 7 00:19:13 EST 2010


* Schif Schaf:
> 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?

I haven't used regexps in Python before, but what I did was (1) look in the 
documentation, (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>


Python's equivalent of the Perl snippet seems to be the same number of lines, 
and more clear. :-)


Cheers & hth.,

- Alf



More information about the Python-list mailing list