Python RegEx

A RegEx, or Regular Expression, is a sequence of characters that forms a search pattern.

RegEx can be used to check if a string contains the specified search pattern.

RegEx Module

Python has a built-in package called re, which can be used to work with Regular Expressions.

Import the re module:

Python image
import re

RegEx in Python

When you have imported the re module, you can start using regular expressions:

Example

Search the string to see if it starts with "The" and ends with "Spain":

Python image
import re

txt = "The rain in Spain"
x = re.search("^The.*Spain$", txt)

RegEx Functions

The re module offers a set of functions that allows us to search a string for a match:

FunctionDescription
findallReturns a list containing all matches
searchReturns a Match object if there is a match anywhere in the string
splitReturns a list where the string has been split at each match
subReplaces one or many matches with a string

Metacharacters

Metacharacters are characters with a special meaning:

CharacterDescriptionExample
[]A set of characters"[a-m]"
\Signals a special sequence"\d"
.Any character (except newline)"he..o"
^Starts with"^hello"
$Ends with"planet$"
*Zero or more occurrences"he.*o"
+One or more occurrences"he.+o"
?Zero or one occurrences"he.?o"
Exactly specified number of occurrences"he{2}o"
|Either or"falls|stays"

Special Sequences

A special sequence is a \ followed by one of the characters below:

\AReturns match if characters are at start of string
\bReturns match where specified characters are at start/end of a word
\dReturns match where string contains digits (0-9)
\sReturns match where string contains white space character
\wReturns match containing word characters (a-Z, 0-9, _)

The findall() Function

The findall() function returns a list containing all matches.

Python image
import re

txt = "The rain in Spain"
x = re.findall("ai", txt)
print(x)

Match Object

A Match Object is an object containing information about the search and the result.

Note: If there is no match, the value None will be returned.
Python image
import re

txt = "The rain in Spain"
x = re.search("ai", txt)
print(x) #this will print an object

The Match object has properties and methods used to retrieve information:

  • span() returns a tuple containing the start- and end positions of the match
  • string returns the string passed into the function.
  • group() returns the part of the string where there was a match.