[regex] Basic rewriting

G

Gilles Ganault

Hello

I've been reading tutorials on regexes in Python, but I still
don't get it:

========
#!/usr/bin/python

#myscript.py 0123456789

import sys,re

#Turn 0123456789 into 01.23.45.67.89
p = re.compile('(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)')
phone = p.sub('\1.\2.\3.\4.\5',sys.argv[1])
print phone
========

=> Python displays "...." instead. Any idea what I'm doing wrong?

Thank you.
 
T

Tim Chase

I've been reading tutorials on regexes in Python, but I still
don't get it:

========
#!/usr/bin/python

#myscript.py 0123456789

import sys,re

#Turn 0123456789 into 01.23.45.67.89
p = re.compile('(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)')
phone = p.sub('\1.\2.\3.\4.\5',sys.argv[1])
print phone
========

=> Python displays "...." instead. Any idea what I'm doing wrong?


Looks like you need to use "raw" strings of the form

r'...'

Otherwise, you'd need to escape every backslash so that the
regexp parser actually gets it. Thus you can either do this:

p = re.compile(r'(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)')
phone = p.sub(r'\1.\2.\3.\4.\5',sys.argv[1])

or the much more hideous:

p = re.compile('(\\d\\d)(\\d\\d)(\\d\\d)(\\d\\d)(\\d\\d)')
phone = p.sub('\\1.\\2.\\3.\\4.\\5',sys.argv[1])

HTH,

-tkc
 
J

J. Clifford Dyer

Hello

I've been reading tutorials on regexes in Python, but I still
don't get it:

========
#!/usr/bin/python

#myscript.py 0123456789

import sys,re

#Turn 0123456789 into 01.23.45.67.89
p = re.compile('(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)')
phone = p.sub('\1.\2.\3.\4.\5',sys.argv[1])
print phone
========

=> Python displays "...." instead. Any idea what I'm doing wrong?

Thank you.

Use raw strings for re expressions.

r'this is a raw string'
'this is not'

p = re.compile(r'(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)')
phone = p.sub(r'\1.\2.\3.\4.\5',sys.argv[1])

Should clear up your problem.
 

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,774
Messages
2,569,596
Members
45,143
Latest member
DewittMill
Top