spaces in re.compile()

R

rbt

Is it possible to use spaces in a re.compile()?

For example, I want to make sure one space exists right before this
string and right after it:

re.compile ('\d{3,3}\.\d{3,3}\.\d{3,3}\.\d{3,3}')

I've tried this, but it didn't work:

re.compile (' \d{3,3}\.\d{3,3}\.\d{3,3}\.\d{3,3} ')

Any ideas?
 
R

rbt

AndrewN said:
[' 123.345.678 ']

Works for me.

Yes, you're correct. That works if there is a space at the front and
back. However, place '123.345.678' in a file by itself and it doesn't work.

What I'm trying to avoid is something like this '1234.345.6789' Notice
the 4 chars in the first and last part? findall gets '234.345.678' and
returns positive... I thought that by requiring spaces I could avoid
matches such as this, but I was wrong. How can I get what I'm looking
for w/o getting the other stuff as well?
 
J

Jeff Epler

Maybe you want r'\b'. From 'pydoc sre':
\b Matches the empty string, but only at the start or end of a word.


import re
r = re.compile( r'\btest\b' )
print r.findall("testy")
print r.findall(" testy ")
print r.findall(" test ")
print r.findall("test")

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.1 (GNU/Linux)

iD8DBQFCPvoAJd01MZaTXX0RAnydAJ9kzAGXlvU3vrtF0qh6+dyxMB9teACfSYo4
D2BjxuSvqmsCTzlA9f+gBhM=
=DaV2
-----END PGP SIGNATURE-----
 
R

rbt

Jeff said:
Maybe you want r'\b'. From 'pydoc sre':
\b Matches the empty string, but only at the start or end of a word.


import re
r = re.compile( r'\btest\b' )
print r.findall("testy")
print r.findall(" testy ")
print r.findall(" test ")
print r.findall("test")

That works great. Thanks for the tip!
 

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,768
Messages
2,569,574
Members
45,049
Latest member
Allen00Reed

Latest Threads

Top