[Tutor] regular expressions - backslashes

Kent Johnson kent37 at tds.net
Fri Apr 7 04:47:18 CEST 2006


Justin Ezequiel wrote:

> will try to convince my colleague to use string formatting
> if he insists on regexp then he can do
> re.sub(r'(?i)<apppath>', apppath.replace('\\', '\\\\'), template)
> 
> re.escape does not quite work for my example
> 
>>>> re.sub(r'(?i)<apppath>', re.escape(apppath), template)
> 'C\\:\\napp\\_and\\_author\\_query\\napp\\_and\\_author\\_query\\a\\
> b\\ c\\ d\\files'
>>>> print re.sub(r'(?i)<apppath>', re.escape(apppath), template)
> C\:\napp\_and\_author\_query\napp\_and\_author\_query\a\ b\ c\ d\files

OK, I didn't realize re.escape() was so aggressive. Depending on how you 
are going to use the file paths, another alternative is just to use / 
instead of \, that will work fine within Python even on Windows.

Kent



More information about the Tutor mailing list