regular expression conundrum

Duncan Booth duncan at NOSPAMrcp.co.uk
Thu Aug 15 11:32:30 CEST 2002


Chris Spencer <clspence at one.net> wrote in
news:5k6llu4k7vrgli643e2fqg9qnlope6bcoq at 4ax.com: 

>      I'm building a string that will be eval()-ed.  I'm building a
>      string 
> which will include Windows path names.  Some of my users, not knowing
> Python, will do something like this: "d:\foo\bar\"+filename
>      When eval()-ed, the " is escaped by the final backslash in the
>      directory 
> string.  I'm making it easy on them by giving them an option to
> wholesale escape all backslashes.  But just in case they did it RIGHT
> by typing: "d:\foo\bar\\"+filename  I want to make sure that the final
> two backslashes aren't escaped again, causing two backslashes to be
> present in an eval(). 
> 
I'm not sure I would call "d:\foo\bar\\" right in any case, let alone 
uppercase. Generally speaking formfeeds and backspaces are best left out of 
filenames.

Given that under Windows either '\' or '/' may be used as path separators, 
you could just deny them any escapes sequences in the strings and do 
eval(replace(s, '\\', '/')). If you want you can then normalise the paths 
using os.path.normpath.

If you must use eval, then at least restrict the available functions. In 
fact give your users a new set of builtins taken from os.path, such as 
join, normpath, expandvars. os.path.join('d:\\foo\\bar\\', filename) and 
os.path.join('d:\\foo\\bar', filename) both work, so if you get into the 
habit of using it, you never need to put a trailing backslash on a path.

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?



More information about the Python-list mailing list