Regular expressions newbie: something for templates
Darrell
dgallion1 at yahoo.com
Sun Mar 10 20:05:28 EST 2002
Skip's example would be faster than mine because I used .*? which has
problems when the amount of content matched is large.
Another way to spell this:
re.sub("\$([^$]+)\$","%(\g<1>)s",s)
or:
re.sub("\$(?P<body>[^$]+)\$","%(\g<body>)s",s)
Also Skip used a raw string r"xxx" which I should have done as well.
The doc explains the problem with not using raw strings.
Has to do with back slash hell.
Now if I can make all this nice stuff a habit :)
--Darrell
Skip Montanaro wrote:
> >>> import re
> >>> s = "This is the test $var1$ and this is $var2$"
> >>> re.sub(r"\$([a-zA-Z_0-9]+)\$", r"%(\1)s", s)
> 'This is the test %(var1)s and this is %(var2)s'
>
More information about the Python-list
mailing list