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
else:
    # no match      

Extract group matches

re.match(regex,string)

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 = matches.group(1) 

    second_group_match = matches.group(2)

    print(first_group_match+" AND "+second_group_match) 

    # prints: "abc AND def"

Replace occurrences of a regex

re.sub(regex,replacement,string)

import re

# re.sub(regex,replacement,string)
re.sub('\d','#','123foo456')
# 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"
re.sub(extension_pattern,r'\1.MYEXT',"foo.txt")
# returns foo.MYEXT

# replace the file name with "MYFILE"
re.sub(extension_pattern,r'MYFILE.\2',"foo.txt")
# returns MYFILE.txt

See also

Replacing a static string:

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

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

Dialogue & Discussion