SlideShare a Scribd company logo
Python Regular Expressions
Megha V
Research Scholar
Kannur University
06-04-2022 meghav@kannuruniv.ac.in 1
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
06-04-2022 meghav@kannuruniv.ac.in 2
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
txt = "The rain in Spain"
x = re.search("^The.*Spain$", txt)
06-04-2022 meghav@kannuruniv.ac.in 3
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
06-04-2022 meghav@kannuruniv.ac.in 4
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 escape special characters)
"d"
. 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
06-04-2022 meghav@kannuruniv.ac.in 5
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 beginning of the string "AThe"
b Returns a match where the specified characters are at the beginning or at the end of a
word
(the "r" in the beginning is making sure that the string is being treated as a "raw string")
r"bain"
r"ainb"
B Returns a match where the specified characters are present, but NOT at the beginning (or
at the end) of a word
(the "r" in the beginning is making sure that the string is being treated as a "raw string")
r"Bain"
r"ainB"
d Returns a match where the string contains digits (numbers from 0-9) "d"
D Returns a match where the string DOES NOT contain digits "D"
s Returns a match where the string contains a white space character "s"
S Returns a match where the string DOES NOT contain a white space character "S"
w Returns a match where the string contains any word characters (characters from a to Z,
digits from 0-9, and the underscore _ character)
"w"
W Returns a match where the string DOES NOT contain any word characters "W"
Z Returns a match if the specified characters are at the end of the string "SpainZ"
06-04-2022 meghav@kannuruniv.ac.in 6
The findall() Function
• 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) #['ai', 'ai']
• The list contains the matches in the order they are found.
• If no matches are found, an empty list is returned:
06-04-2022 meghav@kannuruniv.ac.in 7
• Example
• Return an empty list if no match was found:
import re
txt = "The rain in Spain"
x = re.findall("Portugal", txt)
print(x) #[ ]
06-04-2022 meghav@kannuruniv.ac.in 8
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:
06-04-2022 meghav@kannuruniv.ac.in 9
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:
06-04-2022 meghav@kannuruniv.ac.in 10
Example
• Make a search that returns no match:
import re
txt = "The rain in Spain"
x = re.search("Portugal", txt)
print(x)
06-04-2022 meghav@kannuruniv.ac.in 11
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:
06-04-2022 meghav@kannuruniv.ac.in 12
Example
•Split the string only at the first occurrence:
import re
txt = "The rain in Spain"
x = re.split("s", txt, 1)
print(x)
06-04-2022 meghav@kannuruniv.ac.in 13
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:
06-04-2022 meghav@kannuruniv.ac.in 14
Example
• Replace the first 2 occurrences:
import re
txt = "The rain in Spain"
x = re.sub("s", "9", txt, 2)
print(x)
06-04-2022 meghav@kannuruniv.ac.in 15
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.
06-04-2022 meghav@kannuruniv.ac.in 16
Example
• Do a search that will return a Match Object:
import re
txt = "The rain in Spain"
x = re.search("ai", txt)
print(x) #this will print an object
Output
<re.Match object; span=(5, 7), match='ai'>
06-04-2022 meghav@kannuruniv.ac.in 17
• 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
06-04-2022 meghav@kannuruniv.ac.in 18
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"bSw+", txt)
print(x.span()) # (12, 17)
06-04-2022 meghav@kannuruniv.ac.in 19
Example
• Print the string passed into the function:
import re
txt = "The rain in Spain"
x = re.search(r"bSw+", txt)
print(x.string)
Output
The rain in Spain
06-04-2022 meghav@kannuruniv.ac.in 20
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"bSw+", txt)
print(x.group()) #Spain
06-04-2022 meghav@kannuruniv.ac.in 21
Named Groups with Regular Expressions
• Groups are used in Python in order to reference regular expression
matches.
• By default, groups, without names, are referenced according to
numerical order starting with 1 .
• Let's say we have a regular expression that has 3 subexpressions.
• A user enters in his birthdate, according to the month, day, and year.
• Let's say the user must first enter the month, then the day, and then the
year.
06-04-2022 meghav@kannuruniv.ac.in 22
Named Groups with Regular Expressions
• Using the group() function in Python, without named groups, the first
match (the month) would be referenced using the statement, group(1).
• The second match (the day) would be referenced using the statement,
group(2).
• The third match (the year) would be referenced using the statement,
group(3).
06-04-2022 meghav@kannuruniv.ac.in 23
Named Groups with Regular Expressions
• Now, with named groups, we can name each match in the regular
expression.
• So instead of referencing matches of the regular expression with numbers
(group(1), group(2), etc.), we can reference matches with names, such as
group('month'), group('day'), group('year').
• Named groups makes the code more organized and more readable.
06-04-2022 meghav@kannuruniv.ac.in 24
Named Groups with Regular Expressions
• By seeing, group(1), you don't really know what this represents.
• But if you see, group('month') or group('year'), you know it's referencing
the month or the year.
• So named groups makes code more readable and more understandable
rather than the default numerical referencing.
06-04-2022 meghav@kannuruniv.ac.in 25
Example
>>> import re
>>> string1= "June 15, 1987"
>>> regex= r"^(?P<month>w+)s(?P<day>d+),?s(?P<year>d+)"
>>> matches= re.search(regex, string1)
>>> print("Month: ", matches.group('month'))
>>> print("Day: ", matches.group('day'))
>>> print("Year: ", matches.group('year’))
Output
Month: June
Day: 15
Year: 1987
06-04-2022 meghav@kannuruniv.ac.in 26
Ad

More Related Content

What's hot (20)

Python programming : Classes objects
Python programming : Classes objectsPython programming : Classes objects
Python programming : Classes objects
Emertxe Information Technologies Pvt Ltd
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
Maulik Borsaniya
 
Python : Data Types
Python : Data TypesPython : Data Types
Python : Data Types
Emertxe Information Technologies Pvt Ltd
 
Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and Packages
Damian T. Gordon
 
Python programming : Strings
Python programming : StringsPython programming : Strings
Python programming : Strings
Emertxe Information Technologies Pvt Ltd
 
Python programming : Files
Python programming : FilesPython programming : Files
Python programming : Files
Emertxe Information Technologies Pvt Ltd
 
Python programming : Arrays
Python programming : ArraysPython programming : Arrays
Python programming : Arrays
Emertxe Information Technologies Pvt Ltd
 
6-Python-Recursion PPT.pptx
6-Python-Recursion PPT.pptx6-Python-Recursion PPT.pptx
6-Python-Recursion PPT.pptx
Venkateswara Babu Ravipati
 
Gui programming
Gui programmingGui programming
Gui programming
manikanta361
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
moazamali28
 
Object Oriented Programming Concepts using Java
Object Oriented Programming Concepts using JavaObject Oriented Programming Concepts using Java
Object Oriented Programming Concepts using Java
Glenn Guden
 
Python - Numpy/Pandas/Matplot Machine Learning Libraries
Python - Numpy/Pandas/Matplot Machine Learning LibrariesPython - Numpy/Pandas/Matplot Machine Learning Libraries
Python - Numpy/Pandas/Matplot Machine Learning Libraries
Andrew Ferlitsch
 
Dynamic memory allocation in c
Dynamic memory allocation in cDynamic memory allocation in c
Dynamic memory allocation in c
lavanya marichamy
 
What is Python Lambda Function? Python Tutorial | Edureka
What is Python Lambda Function? Python Tutorial | EdurekaWhat is Python Lambda Function? Python Tutorial | Edureka
What is Python Lambda Function? Python Tutorial | Edureka
Edureka!
 
Python : Functions
Python : FunctionsPython : Functions
Python : Functions
Emertxe Information Technologies Pvt Ltd
 
Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
Praveen M Jigajinni
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
Abhilash Nair
 
Wrapper class
Wrapper classWrapper class
Wrapper class
kamal kotecha
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in python
TMARAGATHAM
 
Two dimensional array
Two dimensional arrayTwo dimensional array
Two dimensional array
Rajendran
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
Maulik Borsaniya
 
Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and Packages
Damian T. Gordon
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
moazamali28
 
Object Oriented Programming Concepts using Java
Object Oriented Programming Concepts using JavaObject Oriented Programming Concepts using Java
Object Oriented Programming Concepts using Java
Glenn Guden
 
Python - Numpy/Pandas/Matplot Machine Learning Libraries
Python - Numpy/Pandas/Matplot Machine Learning LibrariesPython - Numpy/Pandas/Matplot Machine Learning Libraries
Python - Numpy/Pandas/Matplot Machine Learning Libraries
Andrew Ferlitsch
 
Dynamic memory allocation in c
Dynamic memory allocation in cDynamic memory allocation in c
Dynamic memory allocation in c
lavanya marichamy
 
What is Python Lambda Function? Python Tutorial | Edureka
What is Python Lambda Function? Python Tutorial | EdurekaWhat is Python Lambda Function? Python Tutorial | Edureka
What is Python Lambda Function? Python Tutorial | Edureka
Edureka!
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
Abhilash Nair
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in python
TMARAGATHAM
 
Two dimensional array
Two dimensional arrayTwo dimensional array
Two dimensional array
Rajendran
 

Similar to Python- Regular expression (20)

regular-expression.pdf
regular-expression.pdfregular-expression.pdf
regular-expression.pdf
DarellMuchoko
 
unit-4 regular expression.pptx
unit-4 regular expression.pptxunit-4 regular expression.pptx
unit-4 regular expression.pptx
PadreBhoj
 
foundation class python week 4- Strings.pptx
foundation class python week 4- Strings.pptxfoundation class python week 4- Strings.pptx
foundation class python week 4- Strings.pptx
MarufFarhanRigan1
 
NUMPY-2.pptx
NUMPY-2.pptxNUMPY-2.pptx
NUMPY-2.pptx
MahendraVusa
 
Module 3 - Regular Expressions, Dictionaries.pdf
Module 3 - Regular  Expressions,  Dictionaries.pdfModule 3 - Regular  Expressions,  Dictionaries.pdf
Module 3 - Regular Expressions, Dictionaries.pdf
GaneshRaghu4
 
Arrays.pptx
Arrays.pptxArrays.pptx
Arrays.pptx
Epsiba1
 
Computer programming 2 Lesson 10
Computer programming 2  Lesson 10Computer programming 2  Lesson 10
Computer programming 2 Lesson 10
MLG College of Learning, Inc
 
Hub102 - JS - Lesson3
Hub102 - JS - Lesson3Hub102 - JS - Lesson3
Hub102 - JS - Lesson3
Tiểu Hổ
 
Java: Regular Expression
Java: Regular ExpressionJava: Regular Expression
Java: Regular Expression
Masudul Haque
 
Builtinfunctions in vbscript and its types.docx
Builtinfunctions in vbscript and its types.docxBuiltinfunctions in vbscript and its types.docx
Builtinfunctions in vbscript and its types.docx
Ramakrishna Reddy Bijjam
 
Algorithm Assignment Help
Algorithm Assignment HelpAlgorithm Assignment Help
Algorithm Assignment Help
Programming Homework Help
 
TD2-JS-functions
TD2-JS-functionsTD2-JS-functions
TD2-JS-functions
Lilia Sfaxi
 
CSC128_Part_1_WrapperClassesAndStrings_CenBNcj.ppt
CSC128_Part_1_WrapperClassesAndStrings_CenBNcj.pptCSC128_Part_1_WrapperClassesAndStrings_CenBNcj.ppt
CSC128_Part_1_WrapperClassesAndStrings_CenBNcj.ppt
rani marri
 
CP PPT_Unit IV computer programming in c.pdf
CP PPT_Unit IV computer programming in c.pdfCP PPT_Unit IV computer programming in c.pdf
CP PPT_Unit IV computer programming in c.pdf
saneshgamerz
 
Python (regular expression)
Python (regular expression)Python (regular expression)
Python (regular expression)
Chirag Shetty
 
Homework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdfHomework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdf
aroraopticals15
 
Array
ArrayArray
Array
Scott Donald
 
C++ Programming Homework Help
C++ Programming Homework HelpC++ Programming Homework Help
C++ Programming Homework Help
C++ Homework Help
 
@codeprogrammer Python Cheat Sheet for Beginners EMERSON EDUARDO RODRIGUES.pdf
@codeprogrammer Python Cheat Sheet for Beginners EMERSON EDUARDO RODRIGUES.pdf@codeprogrammer Python Cheat Sheet for Beginners EMERSON EDUARDO RODRIGUES.pdf
@codeprogrammer Python Cheat Sheet for Beginners EMERSON EDUARDO RODRIGUES.pdf
EMERSON EDUARDO RODRIGUES
 
Address calculation-sort
Address calculation-sortAddress calculation-sort
Address calculation-sort
Vasim Pathan
 
regular-expression.pdf
regular-expression.pdfregular-expression.pdf
regular-expression.pdf
DarellMuchoko
 
unit-4 regular expression.pptx
unit-4 regular expression.pptxunit-4 regular expression.pptx
unit-4 regular expression.pptx
PadreBhoj
 
foundation class python week 4- Strings.pptx
foundation class python week 4- Strings.pptxfoundation class python week 4- Strings.pptx
foundation class python week 4- Strings.pptx
MarufFarhanRigan1
 
Module 3 - Regular Expressions, Dictionaries.pdf
Module 3 - Regular  Expressions,  Dictionaries.pdfModule 3 - Regular  Expressions,  Dictionaries.pdf
Module 3 - Regular Expressions, Dictionaries.pdf
GaneshRaghu4
 
Arrays.pptx
Arrays.pptxArrays.pptx
Arrays.pptx
Epsiba1
 
Hub102 - JS - Lesson3
Hub102 - JS - Lesson3Hub102 - JS - Lesson3
Hub102 - JS - Lesson3
Tiểu Hổ
 
Java: Regular Expression
Java: Regular ExpressionJava: Regular Expression
Java: Regular Expression
Masudul Haque
 
Builtinfunctions in vbscript and its types.docx
Builtinfunctions in vbscript and its types.docxBuiltinfunctions in vbscript and its types.docx
Builtinfunctions in vbscript and its types.docx
Ramakrishna Reddy Bijjam
 
TD2-JS-functions
TD2-JS-functionsTD2-JS-functions
TD2-JS-functions
Lilia Sfaxi
 
CSC128_Part_1_WrapperClassesAndStrings_CenBNcj.ppt
CSC128_Part_1_WrapperClassesAndStrings_CenBNcj.pptCSC128_Part_1_WrapperClassesAndStrings_CenBNcj.ppt
CSC128_Part_1_WrapperClassesAndStrings_CenBNcj.ppt
rani marri
 
CP PPT_Unit IV computer programming in c.pdf
CP PPT_Unit IV computer programming in c.pdfCP PPT_Unit IV computer programming in c.pdf
CP PPT_Unit IV computer programming in c.pdf
saneshgamerz
 
Python (regular expression)
Python (regular expression)Python (regular expression)
Python (regular expression)
Chirag Shetty
 
Homework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdfHomework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdf
aroraopticals15
 
C++ Programming Homework Help
C++ Programming Homework HelpC++ Programming Homework Help
C++ Programming Homework Help
C++ Homework Help
 
@codeprogrammer Python Cheat Sheet for Beginners EMERSON EDUARDO RODRIGUES.pdf
@codeprogrammer Python Cheat Sheet for Beginners EMERSON EDUARDO RODRIGUES.pdf@codeprogrammer Python Cheat Sheet for Beginners EMERSON EDUARDO RODRIGUES.pdf
@codeprogrammer Python Cheat Sheet for Beginners EMERSON EDUARDO RODRIGUES.pdf
EMERSON EDUARDO RODRIGUES
 
Address calculation-sort
Address calculation-sortAddress calculation-sort
Address calculation-sort
Vasim Pathan
 
Ad

More from Megha V (20)

Soft Computing Techniques_Part 1.pptx
Soft Computing Techniques_Part 1.pptxSoft Computing Techniques_Part 1.pptx
Soft Computing Techniques_Part 1.pptx
Megha V
 
JavaScript- Functions and arrays.pptx
JavaScript- Functions and arrays.pptxJavaScript- Functions and arrays.pptx
JavaScript- Functions and arrays.pptx
Megha V
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
Megha V
 
Python Exception Handling
Python Exception HandlingPython Exception Handling
Python Exception Handling
Megha V
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
Megha V
 
Python programming -Tuple and Set Data type
Python programming -Tuple and Set Data typePython programming -Tuple and Set Data type
Python programming -Tuple and Set Data type
Megha V
 
Python programming –part 7
Python programming –part 7Python programming –part 7
Python programming –part 7
Megha V
 
Python programming Part -6
Python programming Part -6Python programming Part -6
Python programming Part -6
Megha V
 
Python programming: Anonymous functions, String operations
Python programming: Anonymous functions, String operationsPython programming: Anonymous functions, String operations
Python programming: Anonymous functions, String operations
Megha V
 
Python programming- Part IV(Functions)
Python programming- Part IV(Functions)Python programming- Part IV(Functions)
Python programming- Part IV(Functions)
Megha V
 
Python programming –part 3
Python programming –part 3Python programming –part 3
Python programming –part 3
Megha V
 
Parts of python programming language
Parts of python programming languageParts of python programming language
Parts of python programming language
Megha V
 
Python programming
Python programmingPython programming
Python programming
Megha V
 
Strassen's matrix multiplication
Strassen's matrix multiplicationStrassen's matrix multiplication
Strassen's matrix multiplication
Megha V
 
Solving recurrences
Solving recurrencesSolving recurrences
Solving recurrences
Megha V
 
Algorithm Analysis
Algorithm AnalysisAlgorithm Analysis
Algorithm Analysis
Megha V
 
Algorithm analysis and design
Algorithm analysis and designAlgorithm analysis and design
Algorithm analysis and design
Megha V
 
Genetic algorithm
Genetic algorithmGenetic algorithm
Genetic algorithm
Megha V
 
UGC NET Paper 1 ICT Memory and data
UGC NET Paper 1 ICT Memory and data  UGC NET Paper 1 ICT Memory and data
UGC NET Paper 1 ICT Memory and data
Megha V
 
Seminar presentation on OpenGL
Seminar presentation on OpenGLSeminar presentation on OpenGL
Seminar presentation on OpenGL
Megha V
 
Soft Computing Techniques_Part 1.pptx
Soft Computing Techniques_Part 1.pptxSoft Computing Techniques_Part 1.pptx
Soft Computing Techniques_Part 1.pptx
Megha V
 
JavaScript- Functions and arrays.pptx
JavaScript- Functions and arrays.pptxJavaScript- Functions and arrays.pptx
JavaScript- Functions and arrays.pptx
Megha V
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
Megha V
 
Python Exception Handling
Python Exception HandlingPython Exception Handling
Python Exception Handling
Megha V
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
Megha V
 
Python programming -Tuple and Set Data type
Python programming -Tuple and Set Data typePython programming -Tuple and Set Data type
Python programming -Tuple and Set Data type
Megha V
 
Python programming –part 7
Python programming –part 7Python programming –part 7
Python programming –part 7
Megha V
 
Python programming Part -6
Python programming Part -6Python programming Part -6
Python programming Part -6
Megha V
 
Python programming: Anonymous functions, String operations
Python programming: Anonymous functions, String operationsPython programming: Anonymous functions, String operations
Python programming: Anonymous functions, String operations
Megha V
 
Python programming- Part IV(Functions)
Python programming- Part IV(Functions)Python programming- Part IV(Functions)
Python programming- Part IV(Functions)
Megha V
 
Python programming –part 3
Python programming –part 3Python programming –part 3
Python programming –part 3
Megha V
 
Parts of python programming language
Parts of python programming languageParts of python programming language
Parts of python programming language
Megha V
 
Python programming
Python programmingPython programming
Python programming
Megha V
 
Strassen's matrix multiplication
Strassen's matrix multiplicationStrassen's matrix multiplication
Strassen's matrix multiplication
Megha V
 
Solving recurrences
Solving recurrencesSolving recurrences
Solving recurrences
Megha V
 
Algorithm Analysis
Algorithm AnalysisAlgorithm Analysis
Algorithm Analysis
Megha V
 
Algorithm analysis and design
Algorithm analysis and designAlgorithm analysis and design
Algorithm analysis and design
Megha V
 
Genetic algorithm
Genetic algorithmGenetic algorithm
Genetic algorithm
Megha V
 
UGC NET Paper 1 ICT Memory and data
UGC NET Paper 1 ICT Memory and data  UGC NET Paper 1 ICT Memory and data
UGC NET Paper 1 ICT Memory and data
Megha V
 
Seminar presentation on OpenGL
Seminar presentation on OpenGLSeminar presentation on OpenGL
Seminar presentation on OpenGL
Megha V
 
Ad

Recently uploaded (20)

Handling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptxHandling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptx
AuthorAIDNationalRes
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
Sinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_NameSinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_Name
keshanf79
 
LDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini UpdatesLDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini Updates
LDM Mia eStudios
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Library Association of Ireland
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsepulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
sushreesangita003
 
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Celine George
 
New Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptxNew Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptx
milanasargsyan5
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
Political History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptxPolitical History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptx
Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
Handling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptxHandling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptx
AuthorAIDNationalRes
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
Sinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_NameSinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_Name
keshanf79
 
LDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini UpdatesLDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini Updates
LDM Mia eStudios
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Library Association of Ireland
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsepulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
sushreesangita003
 
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Celine George
 
New Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptxNew Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptx
milanasargsyan5
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 

Python- Regular expression

  • 1. Python Regular Expressions Megha V Research Scholar Kannur University 06-04-2022 [email protected] 1
  • 2. 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 06-04-2022 [email protected] 2
  • 3. 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 txt = "The rain in Spain" x = re.search("^The.*Spain$", txt) 06-04-2022 [email protected] 3
  • 4. 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 06-04-2022 [email protected] 4
  • 5. 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 escape special characters) "d" . 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 06-04-2022 [email protected] 5
  • 6. 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 beginning of the string "AThe" b Returns a match where the specified characters are at the beginning or at the end of a word (the "r" in the beginning is making sure that the string is being treated as a "raw string") r"bain" r"ainb" B Returns a match where the specified characters are present, but NOT at the beginning (or at the end) of a word (the "r" in the beginning is making sure that the string is being treated as a "raw string") r"Bain" r"ainB" d Returns a match where the string contains digits (numbers from 0-9) "d" D Returns a match where the string DOES NOT contain digits "D" s Returns a match where the string contains a white space character "s" S Returns a match where the string DOES NOT contain a white space character "S" w Returns a match where the string contains any word characters (characters from a to Z, digits from 0-9, and the underscore _ character) "w" W Returns a match where the string DOES NOT contain any word characters "W" Z Returns a match if the specified characters are at the end of the string "SpainZ" 06-04-2022 [email protected] 6
  • 7. The findall() Function • 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) #['ai', 'ai'] • The list contains the matches in the order they are found. • If no matches are found, an empty list is returned: 06-04-2022 [email protected] 7
  • 8. • Example • Return an empty list if no match was found: import re txt = "The rain in Spain" x = re.findall("Portugal", txt) print(x) #[ ] 06-04-2022 [email protected] 8
  • 9. 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: 06-04-2022 [email protected] 9
  • 10. 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: 06-04-2022 [email protected] 10
  • 11. Example • Make a search that returns no match: import re txt = "The rain in Spain" x = re.search("Portugal", txt) print(x) 06-04-2022 [email protected] 11
  • 12. 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: 06-04-2022 [email protected] 12
  • 13. Example •Split the string only at the first occurrence: import re txt = "The rain in Spain" x = re.split("s", txt, 1) print(x) 06-04-2022 [email protected] 13
  • 14. 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: 06-04-2022 [email protected] 14
  • 15. Example • Replace the first 2 occurrences: import re txt = "The rain in Spain" x = re.sub("s", "9", txt, 2) print(x) 06-04-2022 [email protected] 15
  • 16. 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. 06-04-2022 [email protected] 16
  • 17. Example • Do a search that will return a Match Object: import re txt = "The rain in Spain" x = re.search("ai", txt) print(x) #this will print an object Output <re.Match object; span=(5, 7), match='ai'> 06-04-2022 [email protected] 17
  • 18. • 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 06-04-2022 [email protected] 18
  • 19. 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"bSw+", txt) print(x.span()) # (12, 17) 06-04-2022 [email protected] 19
  • 20. Example • Print the string passed into the function: import re txt = "The rain in Spain" x = re.search(r"bSw+", txt) print(x.string) Output The rain in Spain 06-04-2022 [email protected] 20
  • 21. 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"bSw+", txt) print(x.group()) #Spain 06-04-2022 [email protected] 21
  • 22. Named Groups with Regular Expressions • Groups are used in Python in order to reference regular expression matches. • By default, groups, without names, are referenced according to numerical order starting with 1 . • Let's say we have a regular expression that has 3 subexpressions. • A user enters in his birthdate, according to the month, day, and year. • Let's say the user must first enter the month, then the day, and then the year. 06-04-2022 [email protected] 22
  • 23. Named Groups with Regular Expressions • Using the group() function in Python, without named groups, the first match (the month) would be referenced using the statement, group(1). • The second match (the day) would be referenced using the statement, group(2). • The third match (the year) would be referenced using the statement, group(3). 06-04-2022 [email protected] 23
  • 24. Named Groups with Regular Expressions • Now, with named groups, we can name each match in the regular expression. • So instead of referencing matches of the regular expression with numbers (group(1), group(2), etc.), we can reference matches with names, such as group('month'), group('day'), group('year'). • Named groups makes the code more organized and more readable. 06-04-2022 [email protected] 24
  • 25. Named Groups with Regular Expressions • By seeing, group(1), you don't really know what this represents. • But if you see, group('month') or group('year'), you know it's referencing the month or the year. • So named groups makes code more readable and more understandable rather than the default numerical referencing. 06-04-2022 [email protected] 25
  • 26. Example >>> import re >>> string1= "June 15, 1987" >>> regex= r"^(?P<month>w+)s(?P<day>d+),?s(?P<year>d+)" >>> matches= re.search(regex, string1) >>> print("Month: ", matches.group('month')) >>> print("Day: ", matches.group('day')) >>> print("Year: ", matches.group('year’)) Output Month: June Day: 15 Year: 1987 06-04-2022 [email protected] 26