By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
444,050 Members | 1,009 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 444,050 IT Pros & Developers. It's quick & easy.

[regex] Basic rewriting

P: n/a
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.
Nov 21 '07 #1
Share this Question
Share on Google+
3 Replies


P: n/a
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
Nov 21 '07 #2

P: n/a
On Wed, 2007-11-21 at 03:24 +0100, Gilles Ganault wrote:
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.

Nov 21 '07 #3

P: n/a
On Tue, 20 Nov 2007 21:57:43 -0500, "J. Clifford Dyer"
<jc*@sdf.lonestar.orgwrote:
>Use raw strings for re expressions.
Thanks guys for the prompt reply :-) Solved it.
Nov 21 '07 #4

This discussion thread is closed

Replies have been disabled for this discussion.