regular expression conundrum

Steve Holden sholden at holdenweb.com
Wed Aug 14 19:37:57 CEST 2002


"Chris Spencer" <clspence at one.net> wrote in message
news:ri3llu4q3642vb3vc1v7fud9peekubcbfi at 4ax.com...
> Okay, so I have this string: d:\foo\bar\\
>
> I've been trying to find a way of detecting single backslash characters
and
> properly escaping them, WITHOUT affecting properly escaped backslashes.
>
> So the end result string is: d:\\foo\\bar\\
>
> Does anyone have ANY idea how to accomplish this in Python?  Doesn't have
to be
> a regular expression.
>
> Any help would be appreciated.
>

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
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
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                                 http://www.holdenweb.com/
Python Web Programming                http://pydish.holdenweb.com/pwp/
-----------------------------------------------------------------------








More information about the Python-list mailing list