Python Regular Expressions: Examples & Reference

Last updated:
Table of Contents

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

Usage examples for regular expressions in Python.

Unless otherwise stated, examples use Python 3

String matches a regex

import re

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

Extract group matches


import re

# this pattern matches things like "foo-bar" or "bar-baz"

# note that we have 2 capture groups, delimited by parens
pattern = "^(\w{3})-(\w{3})$"

string1 = "abc-def"

matches = re.match(pattern,string1)

# re.match() returns None is there is no match
# so you can use a simple 'if'
if matches:
    # match indices start at 1
    first_group_match = 

    second_group_match =

    print(first_group_match+" AND "+second_group_match) 

    # prints: "abc AND def"

Replace occurrences of a regex

If you just need to replace a static string, string.replace() is much, much faster!

Use re.sub(regex,replacement,string)

import re

# re.sub(regex,replacement,string)
# returns '###foo###'

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

Replace with capture groups

Groups are referenced like this: '\1' for first group, '\2' for second group, etc.

Note the use of the r'' modifier for the strings.

Groups are 1-indexed (start at 1, not 0)

import re

# match strings like "foo.txt" and "bar.csv"
extension_pattern = r'(^.+)\.(.+)$'

# replace the extension with "MYEXT"
# returns foo.MYEXT

# replace the file name with "MYFILE"
# returns MYFILE.txt

Replacing a static string:

If you just need to replace a static string, calling string.replace() instead of re.sub is much faster.

"foo bar baz".replace("foo","FOO")
>> "FOO bar baz"

References and other resources

Dialogue & Discussion