Regular Expressions

Note

  • Always use python raw strings (r) when passing a string to compile.

  • Probably better to use Verbose Regular Expressions whenever possible.

Sample

>>> import re
>>> p = re.compile(r'[a-z]+')
>>> m = p.match( 'tempo')
>>> m.group(), m.start(), m.end()
('tempo', 0, 5)
>>> print p.match('tempo')
<MatchObject object 1>
>>> print p.match('')
None

Extract (positive) numbers from a string

From Extract numbers from a string:

>>> import re
>>> re.findall(r'\d+', 'hello 42 I\'m a 32 string 30')
['42', '32', '30']