Jirico
Jirico

Reputation: 1262

Python simple regex

So I have a pattern:

hourPattern = re.compile('\d{2}:\d{2}')

And match against the compiled pattern

hourStart = hourPattern.match('Sat Jan 28 01:15:00 GMT 2012') 

When I print hourStart it gives me None. Any help?

Upvotes: 3

Views: 1976

Answers (2)

Raymond Hettinger
Raymond Hettinger

Reputation: 226181

Switch from the match method to the search method:

>>> hourPattern = re.compile('\d{2}:\d{2}')
>>> hourStart = hourPattern.search('Sat Jan 28 01:15:00 GMT 2012')
>>> hourStart.group()
'01:15'

Upvotes: 0

g.d.d.c
g.d.d.c

Reputation: 47968

Match expects the found value to be at the beginning of the string. You want search.

>>> import re
>>>
>>> s = re.compile('\d+')
>>>
>>> s2 = 'a123'
>>>
>>> s.match(s2)
>>> s.search(s2)
<_sre.SRE_Match object at 0x01E29AD8>

Upvotes: 9

Related Questions