preg_replace?

Alex Martelli aleax at aleax.it
Wed Apr 17 16:49:24 EDT 2002


Philipp Lenssen wrote:

> I am porting a program that I already wrote in VBScript and PHP.
> My current task: I need to replace everything inbetween square brackets
> with "0". In VBScript I did this "by hand" (looping, inString and so on).
> In PHP somebody helped me with the following solution:
> 
>     $s = preg_replace("%\[[^\]]*\]%", "0", $s);
> 
> Even though I've been reading through regex-tutorials in the meantime, I'm
> still not familiar with it. But is there a simple rule how to convert the
> above into Python code? Not only would it solve my current problem but I
> already got some helpful regex's for PHP and could reuse them in the

Python 2.2.1 (#1, Apr 15 2002, 17:55:14)
[GCC 2.96 20000731 (Mandrake Linux 8.1 2.96-0.62mdk)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> ret=r'\[[^\]]*\]'
>>> import re
>>> cre=re.compile(ret)
>>> a='ba[pop]ple[pup]'
>>> cre.sub('0',a)
'ba0ple0'
>>>

I'm not sure what's wrong with your code, but this works for me.


Alex




More information about the Python-list mailing list