Regular expression confusion

Y

York

I have two backslash - a. and I want to replace them with one backslash,
but I failed:
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "/usr/lib/python2.3/sre.py", line 143, in sub
return _compile(pattern, 0).sub(repl, string, count)
File "/usr/lib/python2.3/sre.py", line 258, in _subx
template = _compile_repl(template, pattern)
File "/usr/lib/python2.3/sre.py", line 245, in _compile_repl
raise error, v # invalid expression
sre_constants.error: bogus escape (end of line)
anybody knows why?

Thanks,

York
 
J

John Machin

York said:
I have two backslash - a. and I want to replace them with one backslash,
but I failed:

Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "/usr/lib/python2.3/sre.py", line 143, in sub
return _compile(pattern, 0).sub(repl, string, count)
File "/usr/lib/python2.3/sre.py", line 258, in _subx
template = _compile_repl(template, pattern)
File "/usr/lib/python2.3/sre.py", line 245, in _compile_repl
raise error, v # invalid expression
sre_constants.error: bogus escape (end of line)

anybody knows why?

Yep. There are *two* levels of escaping happening (1) Python compiler
(2) re compiler (in the first two args, but of course only Python in
the 3rd).
To get your single backslash you need to start out with four cooked or
two raw:

| >>> re.sub(r'\\\\', '\\\\', '\\\\')
'\\'
| >>> re.sub(r'\\\\', r'\\', '\\\\')
'\\'

Cheers,
John
 
J

John Machin

York said:
Oh, that's right, the second arg is escaped by re compiler too.

No, that's wrong, you [should] do the escaping, the compiler unescapes
:)

Cheers,
John
 
F

Fredrik Lundh

York said:
I have two backslash - a. and I want to replace them with one backslash,
but I failed:

John has already sorted the RE-specific part of the problem, but it's
also worth noting that using the RE engine for literal strings is over-
kill; an ordinary replace is easier to use and faster:
'\\'

</F>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top