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.
import re
txt = "The rain in Spain"
x = re.search("^The.*Spain$", txt)
RegEx Functions
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
Character Description Example
[] A set of characters "[a-m]"
\ Signals a special sequence (can also be used to escape special "\d"
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
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 at the "\AThe"
beginning of the string
\b Returns a match where the specified characters are at the r"\bain"
beginning or at the end of a word
(the "r" in the beginning is making sure that the string is r"ain\b"
being treated as a "raw string")
\B Returns a match where the specified characters are r"\Bain"
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 digits (numbers "\d"
from 0-9)
\D Returns a match where the string DOES NOT contain "\D"
digits
\s Returns a match where the string contains a white space "\s"
character
\S Returns a match where the string DOES NOT contain a "\S"
white space character
\w Returns a match where the string contains any word "\w"
characters (characters from a to Z, digits from 0-9, and
the underscore _ character)
\W Returns a match where the string DOES NOT contain any "\W"
word characters
\Z Returns a match if the specified characters are at the end "Spain\Z"
of the string
Sets
A set is a set of characters inside a pair of square brackets [] with a special meaning:
Set Description
[arn] Returns a match where one of the specified characters (a, r, or n) is
present
[a-n] Returns a match for any lower case character, alphabetically
between a and n
[^arn] Returns a match for any character EXCEPT a, r, and n
[0123] Returns a match where any of the specified digits (0, 1, 2, or 3) are
present
[0-9] Returns a match for any digit between 0 and 9
[0-5][0-9] Returns a match for any two-digit numbers from 00 and 59
[a-zA-Z] Returns a match for any character alphabetically between a and z, lower
case OR upper case
[+] In sets, +, *, ., |, (), $,{} has no special meaning, so [+] means: return a
match for any + character in the string
The findall() function returns a list containing all matches.
Example
Print a list of all matches:
import re
txt = "The rain in Spain"
x = re.findall("ai", txt)
print(x)
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"
x = re.findall("Portugal", 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.
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 = re.search("\s", txt)
print("The first white-space character is located in position:", x.start())
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 = re.search("Portugal", txt)
print(x)
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
txt = "The rain in Spain"
x = re.split("\s", txt)
print(x)
You can control the number of occurrences by specifying the maxsplit parameter:
Example
Split the string only at the first occurrence:
import re
txt = "The rain in Spain"
x = re.split("\s", txt, 1)
print(x)
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
txt = "The rain in Spain"
x = re.sub("\s", "9", txt)
print(x)
You can control the number of replacements by specifying the count parameter:
Example
Replace the first 2 occurrences:
import re
txt = "The rain in Spain"
x = re.sub("\s", "9", txt, 2)
print(x)
Match Object
A Match Object is an object containing information about the search and the result.
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 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
txt = "The rain in Spain"
x = re.search(r"\bS\w+", txt)
print(x.span())
Example
Print the string passed into the function:
import re
txt = "The rain in Spain"
x = re.search(r"\bS\w+", txt)
print(x.string)
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
txt = "The rain in Spain"
x = re.search(r"\bS\w+", txt)
print(x.group())
from datetime import date
my_date = date(1996, 12, 11)
print("Date passed as argument is", my_date)
from datetime import date
# calling the today
# function of date class
today = date.today()
print("Today's date is", today)
from datetime import date
# date object of today's date
today = date.today()
print("Current year:", today.year)
print("Current month:", today.month)
print("Current day:", today.day)
from datetime import time
Time = time(11, 34, 56)
print("hour =", Time.hour)
print("minute =", Time.minute)
print("second =", Time.second)
print("microsecond =", Time.microsecond)
from datetime import datetime
a = datetime(1999, 12, 12, 12, 12, 12)
print("year =", a.year)
print("month =", a.month)
print("hour =", a.hour)
print("minute =", a.minute)
print("timestamp =", a.timestamp())
from datetime import datetime
# Calling now() function
today = datetime.now()
print("Current date and time is", today)
Directive Description Example
%a Weekday, short version Wed
%A Weekday, full version Wednesday
%w Weekday as a number 0-6, 0 is Sunday z
%d Day of month 01-31 31
%b Month name, short version Dec
%B Month name, full version December
%m Month as a number 01-12 12
%y Year, short version, without century 18
%Y Year, full version 2018
%H Hour 00-23 17
%I Hour 01-12 05
%p AM/PM PM
%M Minute 00-59 41
%S Second 00-59 08
%f Microsecond 000000-999999 548513
%z UTC offset +0100
%Z Timezone CST
%j Day number of year 001-366 365
%U Week number of year, Sunday as the first day of 52
week, 00-53
%W Week number of year, Monday as the first day of 52
week, 00-53
%c Local version of date and time Mon Dec 31
17:41:00 2018
%x Local version of date 12/31/18
%X Local version of time 17:41:00
%% A % character %