Error:

Simple pattern matching (compile)

import re
s1 = 'foo bar baz foo'
s2 = 'Marry had a little lamb'
p = re.compile('foo.*bar.*foo')
m1 = p.match(s1) # <_sre.SRE_Match object at 0x1020e7168>
m2 = p.match(s2) # None

Simple pattern matching (module level)

import re
s1 = 'foo bar baz foo'
s2 = 'Marry had a little lamb'
m1 = re.match(r'foo.*bar.*foo', s1) # <_sre.SRE_Match object at 0x10a618168>
m2 = re.match(r'foo.*bar.*foo', s2) # None

Case-insensitive pattern matching

import re
s1 = 'foo bar baz foo'
s2 = 'Foo Bar Baz Foo'
p = re.compile('foo.*bar.*foo', re.IGNORECASE)
m1 = p.match(s1) # <_sre.SRE_Match object at 0x10cd0c168>
m2 = p.match(s2) # <_sre.SRE_Match object at 0x10cd0c1d0>

Simple pattern substitution

import re
s = 'foooo bar abc'
s = re.sub(r'fo+', 'ABC', s) # 'ABC bar abc'

Match if X is followed by Y

import re
sOk = 'foobar'
sNotOk = 'fooNOTbar'

m1 = re.match(r'foo(?=bar)', sOk) # <_sre.SRE_Match object at 0x10104f168>
m2 = re.match(r'foo(?=bar)', sNotOk) # None

Match if X is not followed by Y

import re
sNotOk = 'foobar'
sOk = 'fooNOTbar'

m1 = re.match(r'foo(?!bar)', sOk) # <_sre.SRE_Match object at 0x107b0a100>
m2 = re.match(r'foo(?!bar)', sNotOk) # None

Do not remember the match

import re
s = 'foo bar baz'
m = re.match(r'(\w+)\s+(?:\w+\s)?(\w+)', s)
m.group(1) # 'foo'
m.group(2) # 'baz'

Swap words

import re
name = 'John Smith'
formalized = re.sub(r'(\w+)\s+(\w+)', '\\2, \\1', name) # 'Smith, John'

Access matched string

import re
name = 'John Smith'
m = re.match(r'(\w+)\s+(\w+)', name)
if m:
    first_name = m.group(1) # 'John'
    last_name = m.group(2) # 'Smith'

Used matched string in substitution

import re
name = 'John Smith'
formalized = re.sub(r'(\w+)\s+(\w+)', '\\2, \\1', name) # 'Smith, John'

Finding the Nth occurrence of a match

import re
s = 'one two three four five'
# fourth word

idx = 0
for w in re.findall('\w+', s):
    idx += 1
    if idx == 4:
        break

w # 'four'

Matching multiple lines

import re
s = '-- data begins here\nfoo\nbar\nbaz\n-- data ends here'
p = re.compile(r'.*begins here\n(.*)-- data ends here', re.DOTALL)
m = p.match(s)
m.group(1) # 'foo\nbar\nbaz\n'

Greedy and non-greedy matches

import re
s = 'foo bar foo'
# Greedy
m1 = re.search(r'f.*o', s)
m1.group(0) # 'foo bar foo'
# Non-Greedy
m2 = re.search(r'f.*?o', s)
m2.group(0) # 'fo'

AND, OR and NOT matches

regexp_foo_or_bar = r'foo|bar'
regexp_foo_and_bar = r'(?=.*foo)(?=.*bar)'
regexp_foo_and_not_bar = r'(?=.*foo)(?!.*bar)'