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

More Related Content

What's hot

python Function
python Function python Function
python Function
Ronak Rathi
 
Python Modules
Python ModulesPython Modules
Python Modules
Nitin Reddy Katkam
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in python
hydpy
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
Devashish Kumar
 
Regular Expressions in Java
Regular Expressions in JavaRegular Expressions in Java
Regular Expressions in Java
OblivionWalker
 
Sparse matrix and its representation data structure
Sparse matrix and its representation data structureSparse matrix and its representation data structure
Sparse matrix and its representation data structure
Vardhil Patel
 
Adv. python regular expression by Rj
Adv. python regular expression by RjAdv. python regular expression by Rj
Adv. python regular expression by Rj
Shree M.L.Kakadiya MCA mahila college, Amreli
 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in Python
Devashish Kumar
 
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
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in python
TMARAGATHAM
 
Python Regular Expressions
Python Regular ExpressionsPython Regular Expressions
Python Regular Expressions
BMS Institute of Technology and Management
 
Python : Data Types
Python : Data TypesPython : Data Types
9 python data structure-2
9 python data structure-29 python data structure-2
9 python data structure-2
Prof. Dr. K. Adisesha
 
Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and Packages
Damian T. Gordon
 
Class, object and inheritance in python
Class, object and inheritance in pythonClass, object and inheritance in python
Class, object and inheritance in python
Santosh Verma
 
Union in c language
Union  in c languageUnion  in c language
Union in c language
tanmaymodi4
 
Variables in python
Variables in pythonVariables in python
Variables in python
Jaya Kumari
 
Control Structures in Python
Control Structures in PythonControl Structures in Python
Control Structures in Python
Sumit Satam
 
Object oriented programming with python
Object oriented programming with pythonObject oriented programming with python
Object oriented programming with python
Arslan Arshad
 
Polynomial reppresentation using Linkedlist-Application of LL.pptx
Polynomial reppresentation using Linkedlist-Application of LL.pptxPolynomial reppresentation using Linkedlist-Application of LL.pptx
Polynomial reppresentation using Linkedlist-Application of LL.pptx
Albin562191
 

What's hot (20)

python Function
python Function python Function
python Function
 
Python Modules
Python ModulesPython Modules
Python Modules
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in python
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
 
Regular Expressions in Java
Regular Expressions in JavaRegular Expressions in Java
Regular Expressions in Java
 
Sparse matrix and its representation data structure
Sparse matrix and its representation data structureSparse matrix and its representation data structure
Sparse matrix and its representation data structure
 
Adv. python regular expression by Rj
Adv. python regular expression by RjAdv. python regular expression by Rj
Adv. python regular expression by Rj
 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in Python
 
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
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in python
 
Python Regular Expressions
Python Regular ExpressionsPython Regular Expressions
Python Regular Expressions
 
Python : Data Types
Python : Data TypesPython : Data Types
Python : Data Types
 
9 python data structure-2
9 python data structure-29 python data structure-2
9 python data structure-2
 
Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and Packages
 
Class, object and inheritance in python
Class, object and inheritance in pythonClass, object and inheritance in python
Class, object and inheritance in python
 
Union in c language
Union  in c languageUnion  in c language
Union in c language
 
Variables in python
Variables in pythonVariables in python
Variables in python
 
Control Structures in Python
Control Structures in PythonControl Structures in Python
Control Structures in Python
 
Object oriented programming with python
Object oriented programming with pythonObject oriented programming with python
Object oriented programming with python
 
Polynomial reppresentation using Linkedlist-Application of LL.pptx
Polynomial reppresentation using Linkedlist-Application of LL.pptxPolynomial reppresentation using Linkedlist-Application of LL.pptx
Polynomial reppresentation using Linkedlist-Application of LL.pptx
 

Similar to Python- Regular expression

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
 
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 ExpressionMasudul Haque
 
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
 
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
C++ Programming Homework Help
C++ Programming Homework HelpC++ Programming Homework Help
C++ Programming Homework Help
C++ Homework Help
 
Address calculation-sort
Address calculation-sortAddress calculation-sort
Address calculation-sort
Vasim Pathan
 
Chapter 10 Exploring arrays, loops, and conditional statements
Chapter 10 Exploring arrays, loops, and conditional statementsChapter 10 Exploring arrays, loops, and conditional statements
Chapter 10 Exploring arrays, loops, and conditional statements
Dr. Ahmed Al Zaidy
 
CAP776Numpy (2).ppt
CAP776Numpy (2).pptCAP776Numpy (2).ppt
CAP776Numpy (2).ppt
ChhaviCoachingCenter
 
CAP776Numpy.ppt
CAP776Numpy.pptCAP776Numpy.ppt
CAP776Numpy.ppt
kdr52121
 

Similar to Python- Regular expression (20)

regular-expression.pdf
regular-expression.pdfregular-expression.pdf
regular-expression.pdf
 
unit-4 regular expression.pptx
unit-4 regular expression.pptxunit-4 regular expression.pptx
unit-4 regular expression.pptx
 
NUMPY-2.pptx
NUMPY-2.pptxNUMPY-2.pptx
NUMPY-2.pptx
 
Module 3 - Regular Expressions, Dictionaries.pdf
Module 3 - Regular  Expressions,  Dictionaries.pdfModule 3 - Regular  Expressions,  Dictionaries.pdf
Module 3 - Regular Expressions, Dictionaries.pdf
 
Arrays.pptx
Arrays.pptxArrays.pptx
Arrays.pptx
 
Computer programming 2 Lesson 10
Computer programming 2  Lesson 10Computer programming 2  Lesson 10
Computer programming 2 Lesson 10
 
Hub102 - JS - Lesson3
Hub102 - JS - Lesson3Hub102 - JS - Lesson3
Hub102 - JS - Lesson3
 
Java: Regular Expression
Java: Regular ExpressionJava: Regular Expression
Java: Regular Expression
 
Algorithm Assignment Help
Algorithm Assignment HelpAlgorithm Assignment Help
Algorithm Assignment Help
 
TD2-JS-functions
TD2-JS-functionsTD2-JS-functions
TD2-JS-functions
 
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
 
Python (regular expression)
Python (regular expression)Python (regular expression)
Python (regular expression)
 
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
 
Array
ArrayArray
Array
 
C++ Programming Homework Help
C++ Programming Homework HelpC++ Programming Homework Help
C++ Programming Homework Help
 
Address calculation-sort
Address calculation-sortAddress calculation-sort
Address calculation-sort
 
Chapter 10 Exploring arrays, loops, and conditional statements
Chapter 10 Exploring arrays, loops, and conditional statementsChapter 10 Exploring arrays, loops, and conditional statements
Chapter 10 Exploring arrays, loops, and conditional statements
 
CAP776Numpy (2).ppt
CAP776Numpy (2).pptCAP776Numpy (2).ppt
CAP776Numpy (2).ppt
 
CAP776Numpy.ppt
CAP776Numpy.pptCAP776Numpy.ppt
CAP776Numpy.ppt
 
Unit ii data structure-converted
Unit  ii data structure-convertedUnit  ii data structure-converted
Unit ii data structure-converted
 

More from 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
 
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
 
Msc project_CDS Automation
Msc project_CDS AutomationMsc project_CDS Automation
Msc project_CDS Automation
Megha V
 

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
 
JavaScript- Functions and arrays.pptx
JavaScript- Functions and arrays.pptxJavaScript- Functions and arrays.pptx
JavaScript- Functions and arrays.pptx
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
 
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
 
Python programming –part 7
Python programming –part 7Python programming –part 7
Python programming –part 7
 
Python programming Part -6
Python programming Part -6Python programming Part -6
Python programming Part -6
 
Python programming: Anonymous functions, String operations
Python programming: Anonymous functions, String operationsPython programming: Anonymous functions, String operations
Python programming: Anonymous functions, String operations
 
Python programming- Part IV(Functions)
Python programming- Part IV(Functions)Python programming- Part IV(Functions)
Python programming- Part IV(Functions)
 
Python programming –part 3
Python programming –part 3Python programming –part 3
Python programming –part 3
 
Parts of python programming language
Parts of python programming languageParts of python programming language
Parts of python programming language
 
Python programming
Python programmingPython programming
Python programming
 
Strassen's matrix multiplication
Strassen's matrix multiplicationStrassen's matrix multiplication
Strassen's matrix multiplication
 
Solving recurrences
Solving recurrencesSolving recurrences
Solving recurrences
 
Algorithm Analysis
Algorithm AnalysisAlgorithm Analysis
Algorithm Analysis
 
Algorithm analysis and design
Algorithm analysis and designAlgorithm analysis and design
Algorithm analysis and design
 
Genetic algorithm
Genetic algorithmGenetic algorithm
Genetic algorithm
 
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
 
Seminar presentation on OpenGL
Seminar presentation on OpenGLSeminar presentation on OpenGL
Seminar presentation on OpenGL
 
Msc project_CDS Automation
Msc project_CDS AutomationMsc project_CDS Automation
Msc project_CDS Automation
 

Recently uploaded

Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
PedroFerreira53928
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
Anna Sz.
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
How to Break the cycle of negative Thoughts
How to Break the cycle of negative ThoughtsHow to Break the cycle of negative Thoughts
How to Break the cycle of negative Thoughts
Col Mukteshwar Prasad
 
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
AzmatAli747758
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
JosvitaDsouza2
 
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdfESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
Fundacja Rozwoju Społeczeństwa Przedsiębiorczego
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
beazzy04
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
Jheel Barad
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
Nguyen Thanh Tu Collection
 
How to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPHow to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERP
Celine George
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
PedroFerreira53928
 
Fish and Chips - have they had their chips
Fish and Chips - have they had their chipsFish and Chips - have they had their chips
Fish and Chips - have they had their chips
GeoBlogs
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 

Recently uploaded (20)

Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
How to Break the cycle of negative Thoughts
How to Break the cycle of negative ThoughtsHow to Break the cycle of negative Thoughts
How to Break the cycle of negative Thoughts
 
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
 
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdfESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
 
How to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPHow to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERP
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
 
Fish and Chips - have they had their chips
Fish and Chips - have they had their chipsFish and Chips - have they had their chips
Fish and Chips - have they had their chips
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 

Python- Regular expression

  • 1. Python Regular Expressions Megha V Research Scholar Kannur University 06-04-2022 meghav@kannuruniv.ac.in 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 meghav@kannuruniv.ac.in 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 meghav@kannuruniv.ac.in 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 meghav@kannuruniv.ac.in 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 meghav@kannuruniv.ac.in 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 meghav@kannuruniv.ac.in 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 meghav@kannuruniv.ac.in 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 meghav@kannuruniv.ac.in 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 meghav@kannuruniv.ac.in 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 meghav@kannuruniv.ac.in 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 meghav@kannuruniv.ac.in 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 meghav@kannuruniv.ac.in 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 meghav@kannuruniv.ac.in 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 meghav@kannuruniv.ac.in 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 meghav@kannuruniv.ac.in 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 meghav@kannuruniv.ac.in 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 meghav@kannuruniv.ac.in 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 meghav@kannuruniv.ac.in 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 meghav@kannuruniv.ac.in 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 meghav@kannuruniv.ac.in 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 meghav@kannuruniv.ac.in 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 meghav@kannuruniv.ac.in 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 meghav@kannuruniv.ac.in 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 meghav@kannuruniv.ac.in 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 meghav@kannuruniv.ac.in 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 meghav@kannuruniv.ac.in 26