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 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":
import re
#Check if the string starts with "The" and ends with "Spain":
txt = "The rain in Spain"
x = [Link]("^The.*Spain$", txt)
if x:
print("YES! We have a match!")
else:
print("No match")
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
The findall() Function
The findall() function returns a list containing all matches.
Example
Print a list of all matches:
import re
#Return a list containing every occurrence of "ai":
txt = "The rain in Spain"
x = [Link]("ai", txt)
print(x)
o/p: ['ai', 'ai']
The list contains the matches in the order they are found.
If no matches are found, an empty list is returned:
Example
Return an empty list if no match was found:
import re
txt = "The rain in Spain"
#Check if "Portugal" is in the string:
x = [Link]("Portugal", txt)
print(x)
if (x):
print("Yes, there is at least one match!")
else:
print("No match")
0/p: []
No match
The search() Function
The search() function searches the string for a match, and returns a Match
object if there is a match.
If there is more than one match, only the first occurrence of the match will
be returned:
Example
Search for the first white-space character in the string:
import re
txt = "The rain in Spain"
x = [Link]("\s", txt)
print("The first white-space character is located in position:", [Link]())
o/p: T The first white-space character is located in position: 3he first
white-space character is located in position: 5
If no matches are found, the value None is returned:
Example
Make a search that returns no match:
import re
txt = "The rain in Spain"
x = [Link]("Portugal", txt)
print(x)
o/p: None
The split() Function
The split() function returns a list where the string has been split at each
match:
Example
Split at each white-space character:
import re
#Split the string at every white-space character:
txt = "The rain in Spain"
x = [Link]("\s", txt)
print(x)
o/p: ['The', 'rain', 'in', 'Spain']
You can control the number of occurrences by specifying
the maxsplit parameter:
Example
Split the string only at the first occurrence:
import re
#Split the string at the first white-space character:
txt = "The rain in Spain"
x = [Link]("\s", txt, 1)
print(x)
o/p: ['The', 'rain in Spain']
The sub() Function
The sub() function replaces the matches with the text of your choice:
Example
Replace every white-space character with the number 9:
import re
#Replace all white-space characters with the digit "9":
txt = "The rain in Spain"
x = [Link]("\s", "9", txt)
print(x)
o/p: The9rain9in9Spain
You can control the number of replacements by specifying
the count parameter:
Example
Replace the first 2 occurrences:
import re
#Replace the first two occurrences of a white-space character with the digit
9:
txt = "The rain in Spain"
x = [Link]("\s", "9", txt, 2)
print(x)
o/p: The9rain9in Spain
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, instead of the
Match Object.
Example
Do a search that will return a Match Object:
import re
#The search() function returns a Match object:
txt = "The rain in Spain"
x = [Link]("ai", txt)
print(x)
o/p: <_sre.SRE_Match object; span=(5, 7), match='ai'>
The Match object has properties and methods used to retrieve information
about the search, and the result:
.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
Example
Print the position (start- and end-position) of the first match occurrence.
The regular expression looks for any words that starts with an upper case
"S":
import re
#Search for an upper case "S" character in the beginning of a word, and
print its position:
txt = "The rain in Spain"
x = [Link](r"\bS\w+", txt)
print([Link]())
o/p: (12, 17)
Example
Print the string passed into the function:
import re
#The string property returns the search string:
txt = "The rain in Spain"
x = [Link](r"\bS\w+", txt)
print([Link])
o/p: The rain in Spain
Example
Print the part of the string where there was a match.
The regular expression looks for any words that starts with an upper case
"S":
import re
#Search for an upper case "S" character in the beginning of a word, and
print the word:
txt = "The rain in Spain"
x = [Link](r"\bS\w+", txt)
print([Link]())
o/p: Spain
Metacharacters
Metacharacters are characters with a special meaning:
Character Description Example
[] A set of characters "[a-m]"
\ Signals a special sequence (can also be used to "\d"
escape special characters)
. Any character (except newline character) "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 the specified number of occurrences "he.{2}o"
| Either or "falls|stays"
() Capture and group
import re
txt = "The rain in Spain"
#Find all lower case characters alphabetically between "a" and "m":
x = [Link]("[a-m]", txt)
print(x)
o/p:
['h', 'e', 'a', 'i', 'i', 'a', 'i']
import re
txt = "That will be 59 dollars"
#Find all digit characters:
x = [Link]("\d", txt)
print(x)
o/p: ['5', '9']
[‘5’,’9’]
import re
txt = "hello planet"
#Search for a sequence that starts with "he", followed by two (any) characters, and an "o":
x = [Link]("he..o", txt)
print(x)
['5', '9']
o/p: ['hello']
import re
txt = "hello planet"
#Check if the string starts with 'hello':
x = [Link]("^hello", txt)
if x:
print("Yes, the string starts with 'hello'")
else:
print("No match")
o/p: Yes, the string starts with 'hello'
import re
txt = "hello planet"
#Check if the string ends with 'planet':
x = [Link]("planet$", txt)
if x:
print("Yes, the string ends with 'planet'")
else:
print("No match")
o/p:
Yes, the string ends with 'planet'
import re
txt = "hello planet"
#Search for a sequence that starts with "he", followed by 0 or more (any) characters, and an "o":
x = [Link]("he.*o", txt)
print(x)
o/p:
['hello']
import re
txt = "hello planet"
#Search for a sequence that starts with "he", followed by 1 or more (any) characters, and an "o":
x = [Link]("he.+o", txt)
print(x)
o/p:
['hello']
import re
txt = "hello planet"
#Search for a sequence that starts with "he", followed by 0 or 1 (any) character, and an "o":
x = [Link]("he.?o", txt)
print(x)
#This time we got no match, because there were not zero, not one, but two characters between
"he" and the "o"
o/p: []
import re
txt = "hello planet"
#Search for a sequence that starts with "he", followed excactly 2 (any) characters, and an "o":
x = [Link]("he.{2}o", txt)
print(x)
o/p:
['hello']
import re
txt = "The rain in Spain falls mainly in the plain!"
#Check if the string contains either "falls" or "stays":
x = [Link]("falls|stays", txt)
print(x)
if x:
print("Yes, there is at least one match!")
else:
print("No match")
o/p:
['falls']
Yes, there is at least one match!
Special Sequences
A special sequence is a \ followed by one of the characters in the list below,
and has a special meaning:
Character Description Example
\A Returns a match if the specified characters are "\AThe"
at the beginning of the string
\b Returns a match where the specified r"\bain"
characters are at the beginning or at the end
of a word r"ain\b"
(the "r" in the beginning is making sure that
the string is being treated as a "raw string")
\B Returns a match where the specified r"\Bain"
characters are present, but NOT at the
beginning (or at the end) of a word r"ain\B"
(the "r" in the beginning is making sure that
the string is being treated as a "raw string")
\d Returns a match where the string contains "\d"
digits (numbers from 0-9)
\D Returns a match where the string DOES NOT "\D"
contain digits
\s Returns a match where the string contains a "\s"
white space character
\S Returns a match where the string DOES NOT "\S"
contain a white space character
\w Returns a match where the string contains any "\w"
word characters (characters from a to Z, digits
from 0-9, and the underscore _ character)
\W Returns a match where the string DOES NOT "\W"
contain any word characters
\Z Returns a match if the specified characters are "Spain\Z"
at the end of the string
There is a difference between the use of both functions. Both return the
first match of a substring found in the string, but [Link]() searches only
from the beginning of the string and return match object if found. But if a
match of substring is found somewhere in the middle of the string, it
returns none.
While [Link]() searches for the whole string even if the string contains
multi-lines and tries to find a match of the substring in all the lines of
string.
Distinctions between [Link]() and [Link]()
Now that we have witnessed the working of [Link]() and [Link]()
functions, let us endeavor to illumine the key distinctions between these two
functions −
Search Scope
[Link]() − Scours the entire input string in search of the pattern.
[Link]() − Restricts its search to the beginning of the input string.
Position of Match
[Link]() − inds the irst occurrence of the pattern, regardless of its position.
[Link]() − Permits a match only if the pattern is discovered at the sacred start of
the input string.
Return Value
[Link]() − returns a match object if the pattern is found; else, returns None.
[Link]() − returns a match object if the pattern is found at the start; else, returns
None.
Performance
[Link]() − Undertakes a thorough search of the entire input string, potentially
affecting performance for extensive strings.
[Link]() − Exhibits ef iciency by focusing on matching the pattern only at the
sacred beginning of the string.