SlideShare a Scribd company logo
1 of 20
Download to read offline
Python
Lecture 7Lecture 7
- Ravi Kiran Khareedi
Regular Expressions
• A regular expression (abbreviated regex or regexp) is a
sequence of characters that forms a search pattern, mainly for
use in pattern matching with strings, or string matching, i.e.
"find and replace"-like operations.
• In Python, the regular expression are made available through re
module
Usage: import
• The functions in the re module checks if a particular string matches
a given regular expression.
Regular Expression : Characters
• Normal Characters
– Characters which match themselves
– Ex: test
• Metacharacters• Metacharacters
– Characters which has special meaning
The meta characters are :
. ^ $ * + ? { } [ ]  | ( )
Regular Expressions: Metacharacters
• [ ]
– Used for specifying a character class, which is a set of characters that you
wish to match.
• Characters can be listed individually, or a range of characters can be
indicated by giving two characters and separating them by a '-'.indicated by giving two characters and separating them by a '-'.
• For example, [abc] will match any of the characters a, b, or c; this is the
same as [a-c], which uses a range to express the same set of characters.
• Few Metacharacters are not active inside classes. Example, [akm$] will
match any of the characters 'a', 'k', 'm', or '$';
– '$' is usually a metacharacter, but inside a character class it’s stripped of its special
nature.
Regular Expressions: MetaCharacters
• ^
– Complements the set inside a class
• We can match the characters not listed within the class by
complementing the set.complementing the set.
This is indicated by including a '^' as the first character of the
class;
• Example: [^5] will match any character except '5'.
• 
– Removes the normal meaning
• Similar to String literals (escape sequence),  allows to remove the
special meaning of the Meta characters.
Regular Expressions: Metacharacters
special meaning of the Meta characters.
• Example: To match a [ or  , we can precede them with a
backslash to remove their special meaning: [ or .
• Few sequences beginning with  have some predefined
meaning
Regular Expression - Metacharacters
• Sequences with special meaning with 
d - Matches any decimal digit; this is equivalent to the class [0-9].
D - Matches any non-digit character; this is equivalent to the class
[^0-9].
s - Matches any whitespace character; this is equivalent to thes - Matches any whitespace character; this is equivalent to the
class [ tnr].
S - Matches any non-whitespace character; this is equivalent to
the class [^ tnr].
w - Matches any alphanumeric character; this is equivalent to the
class [a-zA-Z0-9_].
W - Matches any non-alphanumeric character; this is equivalent
to the class [^a-zA-Z0-9_]
• +
– Matches 1 or more occurrences of preceding expression.
– Ex: ca+t will match cat, caat, caaaaaaat
• *
– Matches 0 or more occurrences of preceding expression.
– Ex: ca*t will match ct, cat, caat, caaaaaaat
Regular Expression – Metacharacters for Repetition
Ex: ca*t will match ct, cat, caat, caaaaaaat
• ?
– Matches 0 or 1 occurrence of preceding expression.
– Ex: home-?brew matches either homebrew or home-brew.
• {m,n}
– m,n are decimal integers. m<= repetition <=n
– Ex: a/{1,3}b will match a/b, a//b, and a///b.
– Default Values of m and n are 0 and infinity
• .
– Matches anything except a newline character
• |
– Logical or
– If A and B are regular expressions, A|B will match any string that matches either A or B.
– | has very low precedence. Crow|Servo will match either Crow or Servo, not Cro, a 'w' or an 'S',
and ervo.
• ^
– Matches the beginning of the line
– print re.search('^From', 'From Here to Eternity')
Regular Expression - Metacharacters
– print re.search('^From', 'From Here to Eternity')
– print re.search('^From', 'Reciting From Memory')
• $
– Matches the end of the line
– print re.search('}$', '{block}')
– print re.search('}$', '{block} ')
– print re.search('}$', '{block}n')
• ()
– Grouping
– (ab)* means 0 or more occurrences of ab that is ababababababab
TASK
• Write a regular expression to match the following:
1. Lower case letters
2. Upper case letters
3. Only digits
4. All letters and digits4. All letters and digits
5. Anything else other than vowels
6. Python or python – There are 3 ways
7. Rube or Ruby
TASK
• For Repetation Cases:
1. Match "rub" or "ruby": the y is optional
2. Match "rub" plus 0 or more y’s
3. Match "rub" plus 1 or more y’s
4. Match exactly 3 digits
5. Match 3 or more digits
6. Match 3, 4, or 5 digits
• Pattern at the beginning or end of the string
1. Match hello at the beginning
2. Match world at the end of the string
Module Functions
• match(r, s, f=0)
– r : Pattern: This is the regular expression to be matched.
s: String: This is the string, which would be searched to match the pattern at the beginning of string.
f: Flags: You can specify different flags using bitwise OR (|). These are modifiers, which are listed in
the table below.
For now lets not worry about Flags
If r matches the start of string s, return a MatchObject , otherwise
return None
If r matches the start of string s, return a MatchObject , otherwise
return None
Functions of match object:
group() : Return the string matched by the RE
start() : Return the starting position of the match
end() : Return the ending position of the match
span() : Return a tuple containing the (start, end) positions of the match
We would use group(num) or groups() function of match object to get matched
expression.
Module Functions
• match() – Example
import re
line = "Cats are smarter than dogs“
matchObj = re.match( '(.*) are (.*)', line)
if matchObj:
print "matchObj.group() : ", matchObj.group()
print "matchObj.group(1) : ", matchObj.group(1)
print "matchObj.group(2) : ", matchObj.group(2)
print "matchObj.groups : ", matchObj.groups()
else:
print "No match!!"
Module Functions
• search(r, s, f=0)
– Similar to match().
TASK:TASK:
Try the previous program with the search().
Module Functions: Matching vs Searching
• The only difference: match checks for a match only at the beginning of
the string, while search checks for a match anywhere in the string
• Try this:
import re
line = "Cats are smarter than dogs";
matchObj = re.match( 'dogs', line, re.I)
if matchObj:
print "match --> matchObj.group() : ", matchObj.group()print "match --> matchObj.group() : ", matchObj.group()
else:
print "No match!!"
searchObj = re.search( 'dogs', line, re.M|re.I)
if searchObj:
print "search --> searchObj.group() : ", searchObj.group()
else:
print "Nothing found!!"
Module Function: Search and Replace
• sub(pattern, repl, string, max=0)
– This method replaces all occurrences of the RE pattern in string with repl,
substituting all occurrences unless max provided. This method would return
modified string.
– Example:
import re
phone = "2004-959-559 # This is Phone Number"
# Delete Python-style comments
num = re.sub('#.*$', "", phone)
print "Phone Num : ", num
# Remove anything other than digits
# Write the code for this
Optional Flags
• Optional flags may be included to control
various aspects of matching. Multiple
modifiers can be combined using a | (OR)
TASK
• Try:
import re
test = "Hi HOW are you"
pat = “how"pat = “how"
b = re.search(pat, test)
if b:
print "Yes"
print b;
• Now try to make it case-insensitive
TASK
• Lets try using the meta characters used in the
previous tasks in a program
References
• https://docs.python.org/2/library/re.html
• http://www.tutorialspoint.com/python/pytho
n_reg_expressions.htmn_reg_expressions.htm

More Related Content

What's hot (20)

Regular Expressions
Regular ExpressionsRegular Expressions
Regular Expressions
 
Regular Expression
Regular ExpressionRegular Expression
Regular Expression
 
Processing Regex Python
Processing Regex PythonProcessing Regex Python
Processing Regex Python
 
Hashes
HashesHashes
Hashes
 
Textpad and Regular Expressions
Textpad and Regular ExpressionsTextpad and Regular Expressions
Textpad and Regular Expressions
 
Java: Regular Expression
Java: Regular ExpressionJava: Regular Expression
Java: Regular Expression
 
Regular expressions in Python
Regular expressions in PythonRegular expressions in Python
Regular expressions in Python
 
16 Java Regex
16 Java Regex16 Java Regex
16 Java Regex
 
Regular expressions
Regular expressionsRegular expressions
Regular expressions
 
Php String And Regular Expressions
Php String  And Regular ExpressionsPhp String  And Regular Expressions
Php String And Regular Expressions
 
Basta mastering regex power
Basta mastering regex powerBasta mastering regex power
Basta mastering regex power
 
Strings in Python
Strings in PythonStrings in Python
Strings in Python
 
Bioinformatica p2-p3-introduction
Bioinformatica p2-p3-introductionBioinformatica p2-p3-introduction
Bioinformatica p2-p3-introduction
 
Python- Regular expression
Python- Regular expressionPython- Regular expression
Python- Regular expression
 
Working with text, Regular expressions
Working with text, Regular expressionsWorking with text, Regular expressions
Working with text, Regular expressions
 
Andrei's Regex Clinic
Andrei's Regex ClinicAndrei's Regex Clinic
Andrei's Regex Clinic
 
Regular Expressions 101 Introduction to Regular Expressions
Regular Expressions 101 Introduction to Regular ExpressionsRegular Expressions 101 Introduction to Regular Expressions
Regular Expressions 101 Introduction to Regular Expressions
 
Regular expressions
Regular expressionsRegular expressions
Regular expressions
 
Regular expression examples
Regular expression examplesRegular expression examples
Regular expression examples
 
Python programming : Strings
Python programming : StringsPython programming : Strings
Python programming : Strings
 

Viewers also liked

Object Oriented Programming in Python
Object Oriented Programming in PythonObject Oriented Programming in Python
Object Oriented Programming in PythonSujith Kumar
 
Regexes and-performance-testing
Regexes and-performance-testingRegexes and-performance-testing
Regexes and-performance-testingdoughellmann
 
La Revolución Digital - José Manuel Casas
La Revolución Digital - José Manuel CasasLa Revolución Digital - José Manuel Casas
La Revolución Digital - José Manuel CasasTic Forum - Movistar
 
Ajax: User Experience
Ajax: User ExperienceAjax: User Experience
Ajax: User Experiencepetrov
 
Python functional programming
Python functional programmingPython functional programming
Python functional programmingGeison Goes
 
Functional Pattern Matching on Python
Functional Pattern Matching on PythonFunctional Pattern Matching on Python
Functional Pattern Matching on PythonDaker Fernandes
 
Object oriented programming with python
Object oriented programming with pythonObject oriented programming with python
Object oriented programming with pythonArslan Arshad
 
Intro to Python Data Analysis in Wakari
Intro to Python Data Analysis in WakariIntro to Python Data Analysis in Wakari
Intro to Python Data Analysis in WakariKarissa Rae McKelvey
 
A Brief Introduction to Regular Expression with Python 2.7.3 Standard Library
A Brief Introduction to Regular Expression with Python 2.7.3 Standard LibraryA Brief Introduction to Regular Expression with Python 2.7.3 Standard Library
A Brief Introduction to Regular Expression with Python 2.7.3 Standard LibraryWen Liao
 
Advanced Python : Static and Class Methods
Advanced Python : Static and Class Methods Advanced Python : Static and Class Methods
Advanced Python : Static and Class Methods Bhanwar Singh Meena
 
Advance OOP concepts in Python
Advance OOP concepts in PythonAdvance OOP concepts in Python
Advance OOP concepts in PythonSujith Kumar
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonSujith Kumar
 
Introduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScriptIntroduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScripttmont
 
Thinking in Functions: Functional Programming in Python
Thinking in Functions: Functional Programming in PythonThinking in Functions: Functional Programming in Python
Thinking in Functions: Functional Programming in PythonAnoop Thomas Mathew
 
Python Tricks That You Can't Live Without
Python Tricks That You Can't Live WithoutPython Tricks That You Can't Live Without
Python Tricks That You Can't Live WithoutAudrey Roy
 
Deploying Flask web app using OpenShift
Deploying Flask web app using OpenShiftDeploying Flask web app using OpenShift
Deploying Flask web app using OpenShiftAbhijeet Kasurde
 
Python Pune October Meetup 2015
Python Pune October Meetup 2015Python Pune October Meetup 2015
Python Pune October Meetup 2015Abhijeet Kasurde
 

Viewers also liked (19)

Object Oriented Programming in Python
Object Oriented Programming in PythonObject Oriented Programming in Python
Object Oriented Programming in Python
 
Regexes and-performance-testing
Regexes and-performance-testingRegexes and-performance-testing
Regexes and-performance-testing
 
La Revolución Digital - José Manuel Casas
La Revolución Digital - José Manuel CasasLa Revolución Digital - José Manuel Casas
La Revolución Digital - José Manuel Casas
 
Ajax: User Experience
Ajax: User ExperienceAjax: User Experience
Ajax: User Experience
 
Python functional programming
Python functional programmingPython functional programming
Python functional programming
 
Functional Pattern Matching on Python
Functional Pattern Matching on PythonFunctional Pattern Matching on Python
Functional Pattern Matching on Python
 
Object oriented programming with python
Object oriented programming with pythonObject oriented programming with python
Object oriented programming with python
 
Python Objects
Python ObjectsPython Objects
Python Objects
 
Intro to Python Data Analysis in Wakari
Intro to Python Data Analysis in WakariIntro to Python Data Analysis in Wakari
Intro to Python Data Analysis in Wakari
 
A Brief Introduction to Regular Expression with Python 2.7.3 Standard Library
A Brief Introduction to Regular Expression with Python 2.7.3 Standard LibraryA Brief Introduction to Regular Expression with Python 2.7.3 Standard Library
A Brief Introduction to Regular Expression with Python 2.7.3 Standard Library
 
Python - Lecture 1
Python - Lecture 1Python - Lecture 1
Python - Lecture 1
 
Advanced Python : Static and Class Methods
Advanced Python : Static and Class Methods Advanced Python : Static and Class Methods
Advanced Python : Static and Class Methods
 
Advance OOP concepts in Python
Advance OOP concepts in PythonAdvance OOP concepts in Python
Advance OOP concepts in Python
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
 
Introduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScriptIntroduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScript
 
Thinking in Functions: Functional Programming in Python
Thinking in Functions: Functional Programming in PythonThinking in Functions: Functional Programming in Python
Thinking in Functions: Functional Programming in Python
 
Python Tricks That You Can't Live Without
Python Tricks That You Can't Live WithoutPython Tricks That You Can't Live Without
Python Tricks That You Can't Live Without
 
Deploying Flask web app using OpenShift
Deploying Flask web app using OpenShiftDeploying Flask web app using OpenShift
Deploying Flask web app using OpenShift
 
Python Pune October Meetup 2015
Python Pune October Meetup 2015Python Pune October Meetup 2015
Python Pune October Meetup 2015
 

Similar to Python - Lecture 7

unit-4 regular expression.pptx
unit-4 regular expression.pptxunit-4 regular expression.pptx
unit-4 regular expression.pptxPadreBhoj
 
regular-expression.pdf
regular-expression.pdfregular-expression.pdf
regular-expression.pdfDarellMuchoko
 
Regular_Expressions.pptx
Regular_Expressions.pptxRegular_Expressions.pptx
Regular_Expressions.pptxDurgaNayak4
 
Module 3 - Regular Expressions, Dictionaries.pdf
Module 3 - Regular  Expressions,  Dictionaries.pdfModule 3 - Regular  Expressions,  Dictionaries.pdf
Module 3 - Regular Expressions, Dictionaries.pdfGaneshRaghu4
 
Regular expressions
Regular expressionsRegular expressions
Regular expressionsRaghu nath
 
Regular Expressions grep and egrep
Regular Expressions grep and egrepRegular Expressions grep and egrep
Regular Expressions grep and egrepTri Truong
 
FUNDAMENTALS OF REGULAR EXPRESSION (RegEX).pdf
FUNDAMENTALS OF REGULAR EXPRESSION (RegEX).pdfFUNDAMENTALS OF REGULAR EXPRESSION (RegEX).pdf
FUNDAMENTALS OF REGULAR EXPRESSION (RegEX).pdfBryan Alejos
 
Don't Fear the Regex - CapitalCamp/GovDays 2014
Don't Fear the Regex - CapitalCamp/GovDays 2014Don't Fear the Regex - CapitalCamp/GovDays 2014
Don't Fear the Regex - CapitalCamp/GovDays 2014Sandy Smith
 
Regular expressions
Regular expressionsRegular expressions
Regular expressionsRaj Gupta
 
3.2 javascript regex
3.2 javascript regex3.2 javascript regex
3.2 javascript regexJalpesh Vasa
 
Week-2: Theory & Practice of Data Cleaning: Regular Expressions in Practice
Week-2: Theory & Practice of Data Cleaning: Regular Expressions in PracticeWeek-2: Theory & Practice of Data Cleaning: Regular Expressions in Practice
Week-2: Theory & Practice of Data Cleaning: Regular Expressions in PracticeBertram Ludäscher
 
Regular expressions in oracle
Regular expressions in oracleRegular expressions in oracle
Regular expressions in oracleLogan Palanisamy
 
Php Chapter 4 Training
Php Chapter 4 TrainingPhp Chapter 4 Training
Php Chapter 4 TrainingChris Chubb
 

Similar to Python - Lecture 7 (20)

unit-4 regular expression.pptx
unit-4 regular expression.pptxunit-4 regular expression.pptx
unit-4 regular expression.pptx
 
regular-expression.pdf
regular-expression.pdfregular-expression.pdf
regular-expression.pdf
 
Regular_Expressions.pptx
Regular_Expressions.pptxRegular_Expressions.pptx
Regular_Expressions.pptx
 
Module 3 - Regular Expressions, Dictionaries.pdf
Module 3 - Regular  Expressions,  Dictionaries.pdfModule 3 - Regular  Expressions,  Dictionaries.pdf
Module 3 - Regular Expressions, Dictionaries.pdf
 
Regular expressions
Regular expressionsRegular expressions
Regular expressions
 
Regular Expressions grep and egrep
Regular Expressions grep and egrepRegular Expressions grep and egrep
Regular Expressions grep and egrep
 
FUNDAMENTALS OF REGULAR EXPRESSION (RegEX).pdf
FUNDAMENTALS OF REGULAR EXPRESSION (RegEX).pdfFUNDAMENTALS OF REGULAR EXPRESSION (RegEX).pdf
FUNDAMENTALS OF REGULAR EXPRESSION (RegEX).pdf
 
Regex posix
Regex posixRegex posix
Regex posix
 
Lecture 10.pdf
Lecture 10.pdfLecture 10.pdf
Lecture 10.pdf
 
Regex lecture
Regex lectureRegex lecture
Regex lecture
 
Don't Fear the Regex - CapitalCamp/GovDays 2014
Don't Fear the Regex - CapitalCamp/GovDays 2014Don't Fear the Regex - CapitalCamp/GovDays 2014
Don't Fear the Regex - CapitalCamp/GovDays 2014
 
Regular Expressions
Regular ExpressionsRegular Expressions
Regular Expressions
 
Regular expressions
Regular expressionsRegular expressions
Regular expressions
 
Intoduction to php strings
Intoduction to php  stringsIntoduction to php  strings
Intoduction to php strings
 
3.2 javascript regex
3.2 javascript regex3.2 javascript regex
3.2 javascript regex
 
Week-2: Theory & Practice of Data Cleaning: Regular Expressions in Practice
Week-2: Theory & Practice of Data Cleaning: Regular Expressions in PracticeWeek-2: Theory & Practice of Data Cleaning: Regular Expressions in Practice
Week-2: Theory & Practice of Data Cleaning: Regular Expressions in Practice
 
2.regular expressions
2.regular expressions2.regular expressions
2.regular expressions
 
Regular expressions in oracle
Regular expressions in oracleRegular expressions in oracle
Regular expressions in oracle
 
Php Chapter 4 Training
Php Chapter 4 TrainingPhp Chapter 4 Training
Php Chapter 4 Training
 
Les08
Les08Les08
Les08
 

More from Ravi Kiran Khareedi (10)

Python - Lecture 12
Python - Lecture 12Python - Lecture 12
Python - Lecture 12
 
Python - Lecture 11
Python - Lecture 11Python - Lecture 11
Python - Lecture 11
 
Python - Lecture 10
Python - Lecture 10Python - Lecture 10
Python - Lecture 10
 
Python - Lecture 9
Python - Lecture 9Python - Lecture 9
Python - Lecture 9
 
Python - Lecture 8
Python - Lecture 8Python - Lecture 8
Python - Lecture 8
 
Python - Lecture 6
Python - Lecture 6Python - Lecture 6
Python - Lecture 6
 
Python - Lecture 5
Python - Lecture 5Python - Lecture 5
Python - Lecture 5
 
Python - Lecture 4
Python - Lecture 4Python - Lecture 4
Python - Lecture 4
 
Python - Lecture 3
Python - Lecture 3Python - Lecture 3
Python - Lecture 3
 
Python - Lecture 2
Python - Lecture 2Python - Lecture 2
Python - Lecture 2
 

Recently uploaded

Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfjimielynbastida
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 

Recently uploaded (20)

Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdf
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 

Python - Lecture 7

  • 1. Python Lecture 7Lecture 7 - Ravi Kiran Khareedi
  • 2. Regular Expressions • A regular expression (abbreviated regex or regexp) is a sequence of characters that forms a search pattern, mainly for use in pattern matching with strings, or string matching, i.e. "find and replace"-like operations. • In Python, the regular expression are made available through re module Usage: import • The functions in the re module checks if a particular string matches a given regular expression.
  • 3. Regular Expression : Characters • Normal Characters – Characters which match themselves – Ex: test • Metacharacters• Metacharacters – Characters which has special meaning The meta characters are : . ^ $ * + ? { } [ ] | ( )
  • 4. Regular Expressions: Metacharacters • [ ] – Used for specifying a character class, which is a set of characters that you wish to match. • Characters can be listed individually, or a range of characters can be indicated by giving two characters and separating them by a '-'.indicated by giving two characters and separating them by a '-'. • For example, [abc] will match any of the characters a, b, or c; this is the same as [a-c], which uses a range to express the same set of characters. • Few Metacharacters are not active inside classes. Example, [akm$] will match any of the characters 'a', 'k', 'm', or '$'; – '$' is usually a metacharacter, but inside a character class it’s stripped of its special nature.
  • 5. Regular Expressions: MetaCharacters • ^ – Complements the set inside a class • We can match the characters not listed within the class by complementing the set.complementing the set. This is indicated by including a '^' as the first character of the class; • Example: [^5] will match any character except '5'.
  • 6. • – Removes the normal meaning • Similar to String literals (escape sequence), allows to remove the special meaning of the Meta characters. Regular Expressions: Metacharacters special meaning of the Meta characters. • Example: To match a [ or , we can precede them with a backslash to remove their special meaning: [ or . • Few sequences beginning with have some predefined meaning
  • 7. Regular Expression - Metacharacters • Sequences with special meaning with d - Matches any decimal digit; this is equivalent to the class [0-9]. D - Matches any non-digit character; this is equivalent to the class [^0-9]. s - Matches any whitespace character; this is equivalent to thes - Matches any whitespace character; this is equivalent to the class [ tnr]. S - Matches any non-whitespace character; this is equivalent to the class [^ tnr]. w - Matches any alphanumeric character; this is equivalent to the class [a-zA-Z0-9_]. W - Matches any non-alphanumeric character; this is equivalent to the class [^a-zA-Z0-9_]
  • 8. • + – Matches 1 or more occurrences of preceding expression. – Ex: ca+t will match cat, caat, caaaaaaat • * – Matches 0 or more occurrences of preceding expression. – Ex: ca*t will match ct, cat, caat, caaaaaaat Regular Expression – Metacharacters for Repetition Ex: ca*t will match ct, cat, caat, caaaaaaat • ? – Matches 0 or 1 occurrence of preceding expression. – Ex: home-?brew matches either homebrew or home-brew. • {m,n} – m,n are decimal integers. m<= repetition <=n – Ex: a/{1,3}b will match a/b, a//b, and a///b. – Default Values of m and n are 0 and infinity
  • 9. • . – Matches anything except a newline character • | – Logical or – If A and B are regular expressions, A|B will match any string that matches either A or B. – | has very low precedence. Crow|Servo will match either Crow or Servo, not Cro, a 'w' or an 'S', and ervo. • ^ – Matches the beginning of the line – print re.search('^From', 'From Here to Eternity') Regular Expression - Metacharacters – print re.search('^From', 'From Here to Eternity') – print re.search('^From', 'Reciting From Memory') • $ – Matches the end of the line – print re.search('}$', '{block}') – print re.search('}$', '{block} ') – print re.search('}$', '{block}n') • () – Grouping – (ab)* means 0 or more occurrences of ab that is ababababababab
  • 10. TASK • Write a regular expression to match the following: 1. Lower case letters 2. Upper case letters 3. Only digits 4. All letters and digits4. All letters and digits 5. Anything else other than vowels 6. Python or python – There are 3 ways 7. Rube or Ruby
  • 11. TASK • For Repetation Cases: 1. Match "rub" or "ruby": the y is optional 2. Match "rub" plus 0 or more y’s 3. Match "rub" plus 1 or more y’s 4. Match exactly 3 digits 5. Match 3 or more digits 6. Match 3, 4, or 5 digits • Pattern at the beginning or end of the string 1. Match hello at the beginning 2. Match world at the end of the string
  • 12. Module Functions • match(r, s, f=0) – r : Pattern: This is the regular expression to be matched. s: String: This is the string, which would be searched to match the pattern at the beginning of string. f: Flags: You can specify different flags using bitwise OR (|). These are modifiers, which are listed in the table below. For now lets not worry about Flags If r matches the start of string s, return a MatchObject , otherwise return None If r matches the start of string s, return a MatchObject , otherwise return None Functions of match object: group() : Return the string matched by the RE start() : Return the starting position of the match end() : Return the ending position of the match span() : Return a tuple containing the (start, end) positions of the match We would use group(num) or groups() function of match object to get matched expression.
  • 13. Module Functions • match() – Example import re line = "Cats are smarter than dogs“ matchObj = re.match( '(.*) are (.*)', line) if matchObj: print "matchObj.group() : ", matchObj.group() print "matchObj.group(1) : ", matchObj.group(1) print "matchObj.group(2) : ", matchObj.group(2) print "matchObj.groups : ", matchObj.groups() else: print "No match!!"
  • 14. Module Functions • search(r, s, f=0) – Similar to match(). TASK:TASK: Try the previous program with the search().
  • 15. Module Functions: Matching vs Searching • The only difference: match checks for a match only at the beginning of the string, while search checks for a match anywhere in the string • Try this: import re line = "Cats are smarter than dogs"; matchObj = re.match( 'dogs', line, re.I) if matchObj: print "match --> matchObj.group() : ", matchObj.group()print "match --> matchObj.group() : ", matchObj.group() else: print "No match!!" searchObj = re.search( 'dogs', line, re.M|re.I) if searchObj: print "search --> searchObj.group() : ", searchObj.group() else: print "Nothing found!!"
  • 16. Module Function: Search and Replace • sub(pattern, repl, string, max=0) – This method replaces all occurrences of the RE pattern in string with repl, substituting all occurrences unless max provided. This method would return modified string. – Example: import re phone = "2004-959-559 # This is Phone Number" # Delete Python-style comments num = re.sub('#.*$', "", phone) print "Phone Num : ", num # Remove anything other than digits # Write the code for this
  • 17. Optional Flags • Optional flags may be included to control various aspects of matching. Multiple modifiers can be combined using a | (OR)
  • 18. TASK • Try: import re test = "Hi HOW are you" pat = “how"pat = “how" b = re.search(pat, test) if b: print "Yes" print b; • Now try to make it case-insensitive
  • 19. TASK • Lets try using the meta characters used in the previous tasks in a program