Python Basics
Python RegEx
Regular expressions
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. Python has a built-in package called re, which can be used to work with Regular Expressions.
RegEx Module
Python has a built-in package called re, which can be used to work with Regular Expressions. Import the re module:
import re
RegEx in Python
When you have imported the re module, you can start using regular expressions:
import re
txt = "The rain in Spain"
x = re.search("^The.*Spain$", txt)
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)
The search() Function
The search() function searches the string for a match, and returns a Match object if there is a match:
import re
txt = "The rain in Spain"
x = re.search("\s", txt)
print("The first white-space character is located in position:", x.start())
The split() Function
The split() function returns a list where the string has been split at each match:
import re
txt = "The rain in Spain"
x = re.split("\s", txt)
print(x)