regular expression conundrum

Chris Spencer clspence at
Wed Aug 14 14:08:09 EDT 2002

	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().


On Wed, 14 Aug 2002 13:37:57 -0400, "Steve Holden" <sholden at>
>In other words, you want to double-up any single backslashes, but leave
>unmodified any already-doubled backslashes? Your easiest way is to match
>either one or two backslashes and replace each match with a
>>>> s = "d:\\foo\\bar\\\\"
>>>> print s # just checking
>>>> p = r"(\\{1,2})"
>>>> re.findall(p, s)
>['\\', '\\', '\\\\']
>>>> print re.sub(p, r"\\\\", s)
>Note the doubling of the backslashes in the replacement argument to
>re.sub -- you can read about that in the docs.
>However, I'm interested in what you are using this for. I presume that the
>context does not allow two consecutive single backslashes (which would be
>indistinguishable from one already-doubled backslash)? Are you processing
>Python programs? I don't understand why you need these double-backslashes
>unless you are writing Python that writes Python.
>puzzled-ly y'rs  - steve
>Steve Holden                       
>Python Web Programming      

More information about the Python-list mailing list