← Python lessons

Python Regex Basics: re.search, re.findall and Patterns

A regular expression (regex) is a pattern that describes text. Python's re module uses one to find words, numbers or codes inside a string.

Read String methods and Import first.

re.search() takes a pattern and a string. It returns a match for the first place the pattern fits, or None when it fits nowhere.

import re

text = "The cat sat on the mat"
match = re.search(r"sat", text)
print(match.group())
print(match.start())
print(re.search(r"dog", text))

match.group() is the text that matched. match.start() is the index where it begins. Check if match: before you use a match, because it may be None.

Find every match with re.findall

re.findall() returns a list of every match, as strings.

import re

text = "Ada scored 12, Ben 7 and Cy 105"
numbers = re.findall(r"\d+", text)
print(numbers)
print(sum(int(n) for n in numbers))

\d+ means "one or more digits". Use int() to turn each match into a number.

Build a pattern from special characters

Most characters match themselves. These ones have a special meaning:

PatternMatches
\done digit, 0 to 9
\wone letter, digit or underscore
\sone space, tab or newline
.any one character except a newline
+the thing before it, one or more times
*the thing before it, zero or more times
?the thing before it, zero or one time
{2}the thing before it, exactly 2 times
import re

log = "Start 09:30, lunch 12:15, home 5:05"
print(re.findall(r"\d{2}:\d{2}", log))
print(re.findall(r"\d+:\d+", log))
print(re.findall(r"colou?r", "color or colour"))

\d{2}:\d{2} needs two digits before the colon, so it skips 5:05. In colou?r, the u is optional.

Ignore upper and lower case

Patterns are case-sensitive. Pass re.IGNORECASE to match any case.

import re

text = "Python, python and PYTHON"
print(re.findall(r"python", text))
print(re.findall(r"python", text, re.IGNORECASE))

Note: Write every pattern as a raw string, such as r"\d+". The r stops Python from reading \ as its own escape, like \n. To match a real ., + or ?, put \ before it: r"3\.14".

See also: Character classes and anchors, Groups and re.sub.

Your turn

Print a list of every hashtag in post. A hashtag is # followed by one or more word characters.

import re

post = "Loving #python and #regex today! #100days"
# add one line: print re.findall() with a pattern for a # and the word characters after it

Expected output

['#python', '#regex', '#100days']

Practise this in the free Python course, where every exercise checks your code instantly.