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:

import reRegEx 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":

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:
| Function | Description |
|---|---|
| findall | Returns a list containing all matches |
| search | Returns a Match object if there is a match anywhere in the string |
| split | Returns a list where the string has been split at each match |
| sub | Replaces one or many matches with a string |
Metacharacters
Metacharacters are characters with a special meaning:
| Character | Description | Example |
|---|---|---|
| [] | 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:
| \A | Returns match if characters are at start of string |
| \b | Returns match where specified characters are at start/end of a word |
| \d | Returns match where string contains digits (0-9) |
| \s | Returns match where string contains white space character |
| \w | Returns match containing word characters (a-Z, 0-9, _) |
The findall() Function
The findall() function returns a list containing all matches.

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.
None will be returned.
import re
txt = "The rain in Spain"
x = re.search("ai", txt)
print(x) #this will print an objectThe Match object has properties and methods used to retrieve information:
span()returns a tuple containing the start- and end positions of the matchstringreturns the string passed into the function.group()returns the part of the string where there was a match.