Regex Question

Peter Otten __peter__ at web.de
Sat Aug 18 11:48:42 EDT 2012


Frank Koshti wrote:

> I need to match, process and replace $foo(x=3), knowing that (x=3) is
> optional, and the token might appear simply as $foo.
> 
> To do this, I decided to use:
> 
> re.compile('\$\w*\(?.*?\)').findall(mystring)
> 
> the issue with this is it doesn't match $foo by itself, and requires
> there to be () at the end.

>>> s = """
... <h1>$foo1</h1>
... <p>$foo2()</p>
... <p>$foo3(anything could go here)</p>
... """
>>> re.compile("(\$\w+(?:\(.*?\))?)").findall(s)
['$foo1', '$foo2()', '$foo3(anything could go here)']





More information about the Python-list mailing list