\number parameter in regular expression

P

Piet

Hi there,
I am trying to understand the correct use of the \number parameter in
pythons regular expressions. I belive that the following should work
import re
pattern = re.compile("([a-zA-Z]*)(.*)(\d{4}-\d{2}-\d{2})\1")
search = pattern.search("Date#ThisIsASpacer2004-09-25Date")
print search.groups()
But it doesn´t, because the RE doesn´t match.
I thought that the "\1" thing indicates that the respective part of
the string in question should match the one that is located in
search.group(1). When I change the script to
import re
pattern = re.compile("([a-zA-Z]*)(.*)(\d{4}-\d{2}-\d{2})")
search = pattern.search("Date#ThisIsASpacer2004-09-25")
print search.groups()
print search.group(1)
I get the expected result:
("Date","#ThisIsASpacer","2004-09-25")
Date
How is the \number parameter used correctly?
Many thanks in advance
Piet
 
M

Michael Hoffman

Piet said:
import re
pattern = re.compile("([a-zA-Z]*)(.*)(\d{4}-\d{2}-\d{2})\1")

You should be using a raw string, r"([a-z...". As a purely stylistic
concern, I found that calling this regex object "pattern" somewhat
confusing since that is normally what one calls the string that is
compiled into a regex.

regex = re.compile(r"([a-zA-Z]*)(.*)(\d{4}-\d{2}-\d{2})\1")
^
('Date', '#ThisIsASpacer', '2004-09-25')
 
M

Michael Fuhr

I am trying to understand the correct use of the \number parameter in
pythons regular expressions. I belive that the following should work
import re
pattern = re.compile("([a-zA-Z]*)(.*)(\d{4}-\d{2}-\d{2})\1")
search = pattern.search("Date#ThisIsASpacer2004-09-25Date")
print search.groups()
But it doesn't, because the RE doesn't match.
I thought that the "\1" thing indicates that the respective part of
the string in question should match the one that is located in
search.group(1).

Read the intro to the re documentation:

http://docs.python.org/lib/module-re.html

Hint: what does \1 mean in a string that's not used as a regular
expression?
 

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

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top