regular expression conundrum

Chris Spencer clspence at one.net
Wed Aug 14 20:08:09 CEST 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().

Chris.

On Wed, 14 Aug 2002 13:37:57 -0400, "Steve Holden" <sholden at holdenweb.com>
wrote:
>In other words, you want to double-up any single backslashes, but leave
>either one or two backslashes and replace each match with a
>doubled-backslash.
>
>>>> s = "d:\\foo\\bar\\\\"
>>>> print s # just checking
>d:\foo\bar\\
>>>> p = r"(\\{1,2})"
>>>> re.findall(p, s)
>['\\', '\\', '\\\\']
>>>> print re.sub(p, r"\\\\", s)
>d:\\foo\\bar\\
>
>Note the doubling of the backslashes in the replacement argument to
>
>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                                 http://www.holdenweb.com/
>Python Web Programming                http://pydish.holdenweb.com/pwp/
>-----------------------------------------------------------------------
>
>
>
>