preg_replace?

Philipp Lenssen lenssen at hitnet.rwth-aachen.de
Wed Apr 17 16:09:02 EDT 2002


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 future.

Anyway, the best (or worst) I did so far is:
    pattern = re.compile(r'(\[[^\]]*\])')
    pattern.sub('0', s)

I'm not convinced this remotely resembles how it's done in Python; it
doesn't cause an error, doesn't do what I want either.

Here's my hoped before after:
    s = "Hello [test] world [bla bla]..." # before regular expression
    s = "Hello 0 world 0..." # after





More information about the Python-list mailing list