[Python-bugs-list] [ python-Bugs-422821 ] re.sub raise error with repl is '\'

noreply@sourceforge.net noreply@sourceforge.net
Wed, 09 May 2001 16:16:44 -0700


Bugs item #422821, was updated on 2001-05-09 16:07
You can respond by visiting: 
http://sourceforge.net/tracker/?func=detail&atid=105470&aid=422821&group_id=5470

Category: Regular Expressions
>Group: Not a Bug
>Status: Closed
>Resolution: Invalid
Priority: 5
Submitted By: eXom (jkuan)
Assigned to: Nobody/Anonymous (nobody)
Summary: re.sub raise error with repl is '\'

Initial Comment:
I try to regular substitution '/' into '\'. So I did
re.sub('/', '\', '/tmp/hello').

An exception is raised as follows:

>>> re.sub('/', '\', '/tmp/hello')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "/usr/local/lib/python2.0/sre.py", line 50, in
sub
    return _compile(pattern, 0).sub(repl, string,
count)
  File "/usr/local/lib/python2.0/sre.py", line 115, in
_sub
    return _subn(pattern, template, string, count)[0]
  File "/usr/local/lib/python2.0/sre.py", line 122, in
_subn
    template = sre_parse.parse_template(template,
pattern)
  File "/usr/local/lib/python2.0/sre_parse.py", line
606, in parse_template
    s = Tokenizer(source)
  File "/usr/local/lib/python2.0/sre_parse.py", line
164, in __init__
    self.__next()
  File "/usr/local/lib/python2.0/sre_parse.py", line
174, in __next
    raise error, "bogus escape"
sre_constants.error: bogus escape

-----------------------------------------------

But if I do re.sub('/', '\\', '/tmp/hello')

>>> re.sub('/', '\\', '/tmp/hello')
'\tmp\hello'

------------------------------------------------

I am using BeOpen-Python-2.0-1 (install rpm file) on
Linux i386 machine.


----------------------------------------------------------------------

>Comment By: Tim Peters (tim_one)
Date: 2001-05-09 16:16

Message:
Logged In: YES 
user_id=31435

Not a bug.  The msg from re is correct:  the regexp you 
passed has no meaning, due to a bogus escape (you passed it 
a lone backslash, but a backslash is a regexp 
metacharacter:  if you want re to use a literal backslash, 
you must escape it with a backslash too).

Get in the habit of using r-strings for regular expressions:

re.sub('/', r'\', '/tmp/hello')

works fine (read the docs for more on r-strings and 
backslash escapes; also see the FAQ).


----------------------------------------------------------------------

You can respond by visiting: 
http://sourceforge.net/tracker/?func=detail&atid=105470&aid=422821&group_id=5470