[Tutor] regExpress
Kent Johnson
kent37 at tds.net
Thu Oct 6 02:06:23 CEST 2005
Eric Walker wrote:
> All,
> If I have something like this:
> import re
> sample = 'myboss:isbad'
> express = re.compile('(.*):(.*))
> answer = re.match(express,sample)
>
> how do I get it to tell me if it was a match or not. I have tried
> answer.match . It just gives me an object pointer or something.
re.match() will return None if there is no match, or a match object if it succeeds. And your syntax isn't quite right, if you compile the re then call match() directly on the compiled object. With re.match() you pass the re string as the first arg and you don't have to compile it. In either case, the methods of the match object give details of the match.
http://docs.python.org/lib/match-objects.html
Finally, you may want to use re.search() instead of match(); match will only match the re at the beginning of the string, kind of like if the re started with '^'.
>>> import re
>>> sample = 'myboss:isbad'
>>> express = re.compile('(.*):(.*)')
>>> answer = express.match(sample)
>>> answer
<_sre.SRE_Match object at 0x008C4A40>
>>> answer.groups()
('myboss', 'isbad')
>>> answer = express.match('No colon here, move along')
>>> answer
>>> print answer
None
Kent
More information about the Tutor
mailing list