preg_replace?

Steve Holden sholden at holdenweb.com
Wed Apr 17 16:44:45 EDT 2002


"Philipp Lenssen" <lenssen at hitnet.rwth-aachen.de> 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
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
>
Well, what's wrong with simply replacing the second statement with

    pattern.sub('[0]', s)

Seems like the simplest solution to my simple mind ...

regards
 Steve







More information about the Python-list mailing list