Python Regular Expressions: Examples & Reference

Last updated:

WIP Alert This is a work in progress. Current information is correct but more content will probably be added in the future.

Unless otherwise stated, examples use Python 3

Verify that a string matches a regex

import re

if re.match('w+','foobar'):
    # match
else:
    # no match      

Replace all occurrences of a regex

import re

re.sub('\d','#','123foo456')
# '###foo###'

# this is the pattern for html tags
re.sub('<[^>]+>','','foo <p> bar')
# 'foo  bar'

See also

Dialogue & Discussion