SlideShare a Scribd company logo
1 of 6
© Prof Mukesh N Tekwani, 2016
1 / 6
Unit I Chap 3 : Python – Regular Expressions
3.1 Concept of Regular Expression
A regular expression is a special sequence of characters that helps you match or
find other strings or sets of strings, using a specialized syntax held in a pattern.
Regular expressions are widely used in text pattern matching, text extraction,
and search-and-replace facility. Regular expressions are also called REs, or
regexes or regex patterns.
The module re provides full support for regular expressions in Python. The re
module raises the exception re.error if an error occurs while compiling or using
a regular expression. We can specify the rules for the set of possible strings that
we want to match; this set might contain English sentences, or e-mail addresses, or
anything you like. You can then ask questions such as “Does this string match the
pattern?”, or “Is there a match for the pattern anywhere in this string?”. You can also
use REs to modify a string or to split it apart in various ways.
The patterns or regular expressions can be defined as follows:
● Literal characters must match exactly. For example, "a" matches "a".
● Concatenated patterns match concatenated targets. For example, "ab"
("a" followed by "b") matches "ab".
● Alternate patterns (separated by a vertical bar) match either of the
alternative patterns. For example, "(aaa)|(bbb)" will match either "aaa"
or "bbb".
● Repeating and optional items:
○ "abc*" matches "ab" followed by zero or more occurrences of "c",
for example, "ab", "abc", "abcc", etc.
○ "abc+" matches "ab" followed by one or more occurrences of "c",
for example, "abc", "abcc", etc, but not "ab".
○ "abc?" matches "ab" followed by zero or one occurrences of "c",
for example, "ab" or "abc".
● Sets of characters -- Characters and sequences of characters in square
brackets form a set; a set matches any character in the set or range. For
example, "[abc]" matches "a" or "b" or "c". And, for example, "[_a-z0-
9]" matches an underscore or any lower-case letter or any digit.
● Groups -- Parentheses indicate a group with a pattern. For example,
"ab(cd)*ef" is a pattern that matches "ab" followed by any number of
occurrences of "cd" followed by "ef", for example, "abef", "abcdef",
"abcdcdef", etc.
● There are special names for some sets of characters, for example "d"
(any digit), "w" (any alphanumeric character), "W" (any non-
alphanumeric character), etc.
© Prof Mukesh N Tekwani, 2016
2 / 6
3.2 Metacharacters
In forming a regular expression we use certain characters as metacharacters.
These characters don’t match themselves but they indicate that some other
thing should be matched.
The complete list of metacharacters is:
. ^ $ * + ? { } [ ]  | ( )
Metacharacters [ and ] : They’re 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 '-'. 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.
If you wanted to match only lowercase letters, your RE would be [a-z].
If you want to match digits between 2 to 7, the RE will be [2-7]
Metacharacter ^ : You can match the characters not listed within the class by
complementing the set. This is indicated by including a '^' as the first
character of the class; '^' outside a character class will simply match the '^'
character.
For example, [^5] will match any character except '5'.
Metacharacter  : Backslash is one of the most important metacharacter. The
backslash can be followed by various characters to signal various special
sequences. It’s also used to escape all the metacharacters so you can still
match them in patterns.
If you need to match a [ or , you can precede them with a backslash to remove
their special meaning: [ or . This will search for the [ character or the 
character.
Metacharacter . :
The . matches anything except a newline character, and there’s an alternate
mode (re.DOTALL) where it will match even a newline. '.' is often used where
you want to match “any character”. Example: ‘x.x’ will match ‘xxx’ and also
‘xyx’.
Special Sequences:
d Matches any decimal digit; this is equivalent to the class [0-9].
© Prof Mukesh N Tekwani, 2016
3 / 6
D Matches any non-digit character; this is equivalent to the class [^0-9].
s Matches any whitespace character.
S Matches any non-whitespace character.
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_].
3.3 The re package: search() and match()
The re package provides two methods to perform queries on an input string.
These methods are:
re.search() and re.match()
re.search() method:
Syntax of search():
re.search(pattern, string)
The description of parameters is as follows:
Parameter Description
pattern It is the regular expression to be matched
string This is the string, which would be searched to
match the pattern anywhere in the string.
The re.search function returns a match object on success, none on failure.
Program 1: RegEx1.py
Write a program to search if a pattern 'aa[bc]*dd' appears in the line
input by the user.
import sys, re
pat = re.compile('aa[bc]*dd')
while 1:
line = input('Enter a line ("q" to quit):')
if line == 'q':
© Prof Mukesh N Tekwani, 2016
4 / 6
break
if pat.search(line):
print ('matched:', line)
else:
print ('no match:', line)
Analysis:
1. We import module re in order to use regular expressions.
2. re.compile() compiles a regular expression so that we can reuse the
compiled regular expression without compiling it repeatedly.
Output:
Enter a line ("q" to quit):aabcdd
matched: aabcdd
Enter a line ("q" to quit):abcd
no match: abcd
Enter a line ("q" to quit):aacd
no match: aacd
Enter a line ("q" to quit):aadd
matched: aadd
Enter a line ("q" to quit):aabcbcdd
matched: aabcbcdd
Enter a line ("q" to quit):aabcdddd
matched: aabcdddd
Enter a line ("q" to quit):q
>>>
Program 2: RegEx2.py
Write a program that searches for the occurrence of the pattern ‘A’ followed
by a single digit, followed by the pattern ‘bb’.
import sys, re
pat = re.compile('A[0-9]bb')
while 1:
line = input('Enter a line ("q" to quit):')
if line == 'q':
break
if pat.search(line):
print ('matched:', line)
else:
© Prof Mukesh N Tekwani, 2016
5 / 6
print ('no match:', line)
In the above program, search is used to search a string and match the first string
from the left. search() searches for the pattern anywhere in the string.
Output:
Enter a line ("q" to quit):A65b
no match: A65b
Enter a line ("q" to quit):A65bb
no match: A65bb
Enter a line ("q" to quit):A6bb
matched: A6bb
Enter a line ("q" to quit):AA6bb
matched: AA6bb
Enter a line ("q" to quit):AA6bbc
matched: AA6bbc
Enter a line ("q" to quit):q
>>>
re.match() method:
Syntax of search():
re.match(pattern, string)
The description of parameters is as follows:
Parameter Description
pattern It is the regular expression to be matched
string This is the string, which would be searched to
match the pattern anywhere in the string.
flags You can specify different flags using bitwise OR (|).
The re.match function returns a match object on success, None on failure.
We use group(num) or groups() function of match object to get matched
expression.
group(num=0) This method returns entire match (or specific
subgroup num)
© Prof Mukesh N Tekwani, 2016
6 / 6
groups() This method returns all matching subgroups in a tuple
** Example of using escape sequence: Start Python and type the
following two lines.
>>> name = 'AlbertnEinstein'
>>> print(name)
The output is as shown below. Note that the n character is a new line
character. This character is treated as a single character. This character
causes the remaining part to appear in the next line
Output:
Albert
Einstein
** Raw Strings: Raw strings are strings with escape characters disabled.
We have to add the character ‘r’ or ‘R’ as a prefix to our strings to make
them raw strings.
Modify the above example as follows:
>>> name = r'AlbertnEinstein'
>>> print (name)
AlbertnEinstein
>>>
Note that the n character had no effect in this case.
IMPORTANT QUESTIONS
1. What is a regular expression? Which module provides support for regular
expressions?
2. What is meant by the following: Literal characters, concatenated patterns,
alternate patterns, repeating and optional items, sets of characters.
3. What is a metacharacter? List the metacharacters used in Python. Explain
the following metacharacters: [ and ], ^,  and .
4. With an example, explain the search and match methods.
5. What is a raw string? Explain with a simple example.

More Related Content

What's hot

Python- Regular expression
Python- Regular expressionPython- Regular expression
Python- Regular expressionMegha V
 
Python Programming - XI. String Manipulation and Regular Expressions
Python Programming - XI. String Manipulation and Regular ExpressionsPython Programming - XI. String Manipulation and Regular Expressions
Python Programming - XI. String Manipulation and Regular ExpressionsRanel Padon
 
Strings in Python
Strings in PythonStrings in Python
Strings in Pythonnitamhaske
 
Regular Expression
Regular ExpressionRegular Expression
Regular ExpressionBharat17485
 
Textpad and Regular Expressions
Textpad and Regular ExpressionsTextpad and Regular Expressions
Textpad and Regular ExpressionsOCSI
 
Java chapter 6 - Arrays -syntax and use
Java chapter 6 - Arrays -syntax and useJava chapter 6 - Arrays -syntax and use
Java chapter 6 - Arrays -syntax and useMukesh Tekwani
 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in PythonDevashish Kumar
 
Php String And Regular Expressions
Php String  And Regular ExpressionsPhp String  And Regular Expressions
Php String And Regular Expressionsmussawir20
 
Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm KristinaBorooah
 
Finaal application on regular expression
Finaal application on regular expressionFinaal application on regular expression
Finaal application on regular expressionGagan019
 
Regular Expressions in PHP
Regular Expressions in PHPRegular Expressions in PHP
Regular Expressions in PHPAndrew Kandels
 

What's hot (20)

Regular expressions
Regular expressionsRegular expressions
Regular expressions
 
Python- Regular expression
Python- Regular expressionPython- Regular expression
Python- Regular expression
 
Python Programming - XI. String Manipulation and Regular Expressions
Python Programming - XI. String Manipulation and Regular ExpressionsPython Programming - XI. String Manipulation and Regular Expressions
Python Programming - XI. String Manipulation and Regular Expressions
 
Python programming : Strings
Python programming : StringsPython programming : Strings
Python programming : Strings
 
Strings in Python
Strings in PythonStrings in Python
Strings in Python
 
Python - Lecture 7
Python - Lecture 7Python - Lecture 7
Python - Lecture 7
 
Regular Expression
Regular ExpressionRegular Expression
Regular Expression
 
Regular Expressions
Regular ExpressionsRegular Expressions
Regular Expressions
 
Textpad and Regular Expressions
Textpad and Regular ExpressionsTextpad and Regular Expressions
Textpad and Regular Expressions
 
Java chapter 6 - Arrays -syntax and use
Java chapter 6 - Arrays -syntax and useJava chapter 6 - Arrays -syntax and use
Java chapter 6 - Arrays -syntax and use
 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in Python
 
Python strings
Python stringsPython strings
Python strings
 
Php String And Regular Expressions
Php String  And Regular ExpressionsPhp String  And Regular Expressions
Php String And Regular Expressions
 
Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm
 
Regular Expression
Regular ExpressionRegular Expression
Regular Expression
 
Andrei's Regex Clinic
Andrei's Regex ClinicAndrei's Regex Clinic
Andrei's Regex Clinic
 
Finaal application on regular expression
Finaal application on regular expressionFinaal application on regular expression
Finaal application on regular expression
 
Strings in python
Strings in pythonStrings in python
Strings in python
 
Regular Expressions in PHP
Regular Expressions in PHPRegular Expressions in PHP
Regular Expressions in PHP
 
Chapter 14 strings
Chapter 14 stringsChapter 14 strings
Chapter 14 strings
 

Viewers also liked

Python reading and writing files
Python reading and writing filesPython reading and writing files
Python reading and writing filesMukesh Tekwani
 
Digital signal and image processing FAQ
Digital signal and image processing FAQDigital signal and image processing FAQ
Digital signal and image processing FAQMukesh Tekwani
 
Java chapter 3 - OOPs concepts
Java chapter 3 - OOPs conceptsJava chapter 3 - OOPs concepts
Java chapter 3 - OOPs conceptsMukesh Tekwani
 
Phases of the Compiler - Systems Programming
Phases of the Compiler - Systems ProgrammingPhases of the Compiler - Systems Programming
Phases of the Compiler - Systems ProgrammingMukesh Tekwani
 
Data communications ch 1
Data communications   ch 1Data communications   ch 1
Data communications ch 1Mukesh Tekwani
 
Chap 3 data and signals
Chap 3 data and signalsChap 3 data and signals
Chap 3 data and signalsMukesh Tekwani
 
Chapter 26 - Remote Logging, Electronic Mail & File Transfer
Chapter 26 - Remote Logging, Electronic Mail & File TransferChapter 26 - Remote Logging, Electronic Mail & File Transfer
Chapter 26 - Remote Logging, Electronic Mail & File TransferWayne Jones Jnr
 
Introduction to systems programming
Introduction to systems programmingIntroduction to systems programming
Introduction to systems programmingMukesh Tekwani
 

Viewers also liked (18)

Html graphics
Html graphicsHtml graphics
Html graphics
 
Data Link Layer
Data Link Layer Data Link Layer
Data Link Layer
 
Html tables examples
Html tables   examplesHtml tables   examples
Html tables examples
 
Java chapter 5
Java chapter 5Java chapter 5
Java chapter 5
 
Java chapter 3
Java   chapter 3Java   chapter 3
Java chapter 3
 
Java chapter 1
Java   chapter 1Java   chapter 1
Java chapter 1
 
Python reading and writing files
Python reading and writing filesPython reading and writing files
Python reading and writing files
 
Jdbc 1
Jdbc 1Jdbc 1
Jdbc 1
 
Digital signal and image processing FAQ
Digital signal and image processing FAQDigital signal and image processing FAQ
Digital signal and image processing FAQ
 
Java misc1
Java misc1Java misc1
Java misc1
 
Java swing 1
Java swing 1Java swing 1
Java swing 1
 
Java chapter 3 - OOPs concepts
Java chapter 3 - OOPs conceptsJava chapter 3 - OOPs concepts
Java chapter 3 - OOPs concepts
 
Java 1-contd
Java 1-contdJava 1-contd
Java 1-contd
 
Phases of the Compiler - Systems Programming
Phases of the Compiler - Systems ProgrammingPhases of the Compiler - Systems Programming
Phases of the Compiler - Systems Programming
 
Data communications ch 1
Data communications   ch 1Data communications   ch 1
Data communications ch 1
 
Chap 3 data and signals
Chap 3 data and signalsChap 3 data and signals
Chap 3 data and signals
 
Chapter 26 - Remote Logging, Electronic Mail & File Transfer
Chapter 26 - Remote Logging, Electronic Mail & File TransferChapter 26 - Remote Logging, Electronic Mail & File Transfer
Chapter 26 - Remote Logging, Electronic Mail & File Transfer
 
Introduction to systems programming
Introduction to systems programmingIntroduction to systems programming
Introduction to systems programming
 

Similar to Python - Regular Expressions

Regular_Expressions.pptx
Regular_Expressions.pptxRegular_Expressions.pptx
Regular_Expressions.pptxDurgaNayak4
 
Python regular expressions
Python regular expressionsPython regular expressions
Python regular expressionsKrishna Nanda
 
Regular expressions
Regular expressionsRegular expressions
Regular expressionsRaj Gupta
 
Maxbox starter20
Maxbox starter20Maxbox starter20
Maxbox starter20Max Kleiner
 
Regular expressions in oracle
Regular expressions in oracleRegular expressions in oracle
Regular expressions in oracleLogan Palanisamy
 
Regular expressions
Regular expressionsRegular expressions
Regular expressionsRaghu nath
 
Module 3 - Regular Expressions, Dictionaries.pdf
Module 3 - Regular  Expressions,  Dictionaries.pdfModule 3 - Regular  Expressions,  Dictionaries.pdf
Module 3 - Regular Expressions, Dictionaries.pdfGaneshRaghu4
 
unit-4 regular expression.pptx
unit-4 regular expression.pptxunit-4 regular expression.pptx
unit-4 regular expression.pptxPadreBhoj
 
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-expression.pdf
regular-expression.pdfregular-expression.pdf
regular-expression.pdfDarellMuchoko
 
Bioinformatica 06-10-2011-p2 introduction
Bioinformatica 06-10-2011-p2 introductionBioinformatica 06-10-2011-p2 introduction
Bioinformatica 06-10-2011-p2 introductionProf. Wim Van Criekinge
 
Chapter 3: Introduction to Regular Expression
Chapter 3: Introduction to Regular ExpressionChapter 3: Introduction to Regular Expression
Chapter 3: Introduction to Regular Expressionazzamhadeel89
 
Strings,patterns and regular expressions in perl
Strings,patterns and regular expressions in perlStrings,patterns and regular expressions in perl
Strings,patterns and regular expressions in perlsana mateen
 
Unit 1-strings,patterns and regular expressions
Unit 1-strings,patterns and regular expressionsUnit 1-strings,patterns and regular expressions
Unit 1-strings,patterns and regular expressionssana mateen
 
String interpolation
String interpolationString interpolation
String interpolationKnoldus Inc.
 
Java căn bản - Chapter9
Java căn bản - Chapter9Java căn bản - Chapter9
Java căn bản - Chapter9Vince Vo
 

Similar to Python - Regular Expressions (20)

Regular_Expressions.pptx
Regular_Expressions.pptxRegular_Expressions.pptx
Regular_Expressions.pptx
 
Python regular expressions
Python regular expressionsPython regular expressions
Python regular expressions
 
Regular expressions
Regular expressionsRegular expressions
Regular expressions
 
Maxbox starter20
Maxbox starter20Maxbox starter20
Maxbox starter20
 
Regular expressions in oracle
Regular expressions in oracleRegular expressions in oracle
Regular expressions in oracle
 
Regular expressions
Regular expressionsRegular expressions
Regular expressions
 
Module 3 - Regular Expressions, Dictionaries.pdf
Module 3 - Regular  Expressions,  Dictionaries.pdfModule 3 - Regular  Expressions,  Dictionaries.pdf
Module 3 - Regular Expressions, Dictionaries.pdf
 
Python data handling
Python data handlingPython data handling
Python data handling
 
2.regular expressions
2.regular expressions2.regular expressions
2.regular expressions
 
unit-4 regular expression.pptx
unit-4 regular expression.pptxunit-4 regular expression.pptx
unit-4 regular expression.pptx
 
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-expression.pdf
regular-expression.pdfregular-expression.pdf
regular-expression.pdf
 
Regex lecture
Regex lectureRegex lecture
Regex lecture
 
Bioinformatica 06-10-2011-p2 introduction
Bioinformatica 06-10-2011-p2 introductionBioinformatica 06-10-2011-p2 introduction
Bioinformatica 06-10-2011-p2 introduction
 
Chapter 3: Introduction to Regular Expression
Chapter 3: Introduction to Regular ExpressionChapter 3: Introduction to Regular Expression
Chapter 3: Introduction to Regular Expression
 
14 ruby strings
14 ruby strings14 ruby strings
14 ruby strings
 
Strings,patterns and regular expressions in perl
Strings,patterns and regular expressions in perlStrings,patterns and regular expressions in perl
Strings,patterns and regular expressions in perl
 
Unit 1-strings,patterns and regular expressions
Unit 1-strings,patterns and regular expressionsUnit 1-strings,patterns and regular expressions
Unit 1-strings,patterns and regular expressions
 
String interpolation
String interpolationString interpolation
String interpolation
 
Java căn bản - Chapter9
Java căn bản - Chapter9Java căn bản - Chapter9
Java căn bản - Chapter9
 

More from Mukesh Tekwani

Computer Science Made Easy - Youtube Channel
Computer Science Made Easy - Youtube ChannelComputer Science Made Easy - Youtube Channel
Computer Science Made Easy - Youtube ChannelMukesh Tekwani
 
The Elphinstonian 1988-College Building Centenary Number (2).pdf
The Elphinstonian 1988-College Building Centenary Number (2).pdfThe Elphinstonian 1988-College Building Centenary Number (2).pdf
The Elphinstonian 1988-College Building Centenary Number (2).pdfMukesh Tekwani
 
ISCE-Class 12-Question Bank - Electrostatics - Physics
ISCE-Class 12-Question Bank - Electrostatics  -  PhysicsISCE-Class 12-Question Bank - Electrostatics  -  Physics
ISCE-Class 12-Question Bank - Electrostatics - PhysicsMukesh Tekwani
 
Hexadecimal to binary conversion
Hexadecimal to binary conversion Hexadecimal to binary conversion
Hexadecimal to binary conversion Mukesh Tekwani
 
Hexadecimal to decimal conversion
Hexadecimal to decimal conversion Hexadecimal to decimal conversion
Hexadecimal to decimal conversion Mukesh Tekwani
 
Hexadecimal to octal conversion
Hexadecimal to octal conversionHexadecimal to octal conversion
Hexadecimal to octal conversionMukesh Tekwani
 
Gray code to binary conversion
Gray code to binary conversion Gray code to binary conversion
Gray code to binary conversion Mukesh Tekwani
 
Decimal to Binary conversion
Decimal to Binary conversionDecimal to Binary conversion
Decimal to Binary conversionMukesh Tekwani
 
Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21Mukesh Tekwani
 
Refraction and dispersion of light through a prism
Refraction and dispersion of light through a prismRefraction and dispersion of light through a prism
Refraction and dispersion of light through a prismMukesh Tekwani
 
Refraction of light at a plane surface
Refraction of light at a plane surfaceRefraction of light at a plane surface
Refraction of light at a plane surfaceMukesh Tekwani
 
Atom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atomAtom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atomMukesh Tekwani
 
Refraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lensesRefraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lensesMukesh Tekwani
 
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGEISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGEMukesh Tekwani
 

More from Mukesh Tekwani (20)

Computer Science Made Easy - Youtube Channel
Computer Science Made Easy - Youtube ChannelComputer Science Made Easy - Youtube Channel
Computer Science Made Easy - Youtube Channel
 
The Elphinstonian 1988-College Building Centenary Number (2).pdf
The Elphinstonian 1988-College Building Centenary Number (2).pdfThe Elphinstonian 1988-College Building Centenary Number (2).pdf
The Elphinstonian 1988-College Building Centenary Number (2).pdf
 
Circular motion
Circular motionCircular motion
Circular motion
 
Gravitation
GravitationGravitation
Gravitation
 
ISCE-Class 12-Question Bank - Electrostatics - Physics
ISCE-Class 12-Question Bank - Electrostatics  -  PhysicsISCE-Class 12-Question Bank - Electrostatics  -  Physics
ISCE-Class 12-Question Bank - Electrostatics - Physics
 
Hexadecimal to binary conversion
Hexadecimal to binary conversion Hexadecimal to binary conversion
Hexadecimal to binary conversion
 
Hexadecimal to decimal conversion
Hexadecimal to decimal conversion Hexadecimal to decimal conversion
Hexadecimal to decimal conversion
 
Hexadecimal to octal conversion
Hexadecimal to octal conversionHexadecimal to octal conversion
Hexadecimal to octal conversion
 
Gray code to binary conversion
Gray code to binary conversion Gray code to binary conversion
Gray code to binary conversion
 
What is Gray Code?
What is Gray Code? What is Gray Code?
What is Gray Code?
 
Decimal to Binary conversion
Decimal to Binary conversionDecimal to Binary conversion
Decimal to Binary conversion
 
Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21
 
Refraction and dispersion of light through a prism
Refraction and dispersion of light through a prismRefraction and dispersion of light through a prism
Refraction and dispersion of light through a prism
 
Refraction of light at a plane surface
Refraction of light at a plane surfaceRefraction of light at a plane surface
Refraction of light at a plane surface
 
Spherical mirrors
Spherical mirrorsSpherical mirrors
Spherical mirrors
 
Atom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atomAtom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atom
 
Refraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lensesRefraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lenses
 
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGEISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
 
Cyber Laws
Cyber LawsCyber Laws
Cyber Laws
 
XML
XMLXML
XML
 

Recently uploaded

Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsMehedi Hasan Shohan
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 

Recently uploaded (20)

Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software Solutions
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 

Python - Regular Expressions

  • 1. © Prof Mukesh N Tekwani, 2016 1 / 6 Unit I Chap 3 : Python – Regular Expressions 3.1 Concept of Regular Expression A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings, using a specialized syntax held in a pattern. Regular expressions are widely used in text pattern matching, text extraction, and search-and-replace facility. Regular expressions are also called REs, or regexes or regex patterns. The module re provides full support for regular expressions in Python. The re module raises the exception re.error if an error occurs while compiling or using a regular expression. We can specify the rules for the set of possible strings that we want to match; this set might contain English sentences, or e-mail addresses, or anything you like. You can then ask questions such as “Does this string match the pattern?”, or “Is there a match for the pattern anywhere in this string?”. You can also use REs to modify a string or to split it apart in various ways. The patterns or regular expressions can be defined as follows: ● Literal characters must match exactly. For example, "a" matches "a". ● Concatenated patterns match concatenated targets. For example, "ab" ("a" followed by "b") matches "ab". ● Alternate patterns (separated by a vertical bar) match either of the alternative patterns. For example, "(aaa)|(bbb)" will match either "aaa" or "bbb". ● Repeating and optional items: ○ "abc*" matches "ab" followed by zero or more occurrences of "c", for example, "ab", "abc", "abcc", etc. ○ "abc+" matches "ab" followed by one or more occurrences of "c", for example, "abc", "abcc", etc, but not "ab". ○ "abc?" matches "ab" followed by zero or one occurrences of "c", for example, "ab" or "abc". ● Sets of characters -- Characters and sequences of characters in square brackets form a set; a set matches any character in the set or range. For example, "[abc]" matches "a" or "b" or "c". And, for example, "[_a-z0- 9]" matches an underscore or any lower-case letter or any digit. ● Groups -- Parentheses indicate a group with a pattern. For example, "ab(cd)*ef" is a pattern that matches "ab" followed by any number of occurrences of "cd" followed by "ef", for example, "abef", "abcdef", "abcdcdef", etc. ● There are special names for some sets of characters, for example "d" (any digit), "w" (any alphanumeric character), "W" (any non- alphanumeric character), etc.
  • 2. © Prof Mukesh N Tekwani, 2016 2 / 6 3.2 Metacharacters In forming a regular expression we use certain characters as metacharacters. These characters don’t match themselves but they indicate that some other thing should be matched. The complete list of metacharacters is: . ^ $ * + ? { } [ ] | ( ) Metacharacters [ and ] : They’re 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 '-'. 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. If you wanted to match only lowercase letters, your RE would be [a-z]. If you want to match digits between 2 to 7, the RE will be [2-7] Metacharacter ^ : You can match the characters not listed within the class by complementing the set. This is indicated by including a '^' as the first character of the class; '^' outside a character class will simply match the '^' character. For example, [^5] will match any character except '5'. Metacharacter : Backslash is one of the most important metacharacter. The backslash can be followed by various characters to signal various special sequences. It’s also used to escape all the metacharacters so you can still match them in patterns. If you need to match a [ or , you can precede them with a backslash to remove their special meaning: [ or . This will search for the [ character or the character. Metacharacter . : The . matches anything except a newline character, and there’s an alternate mode (re.DOTALL) where it will match even a newline. '.' is often used where you want to match “any character”. Example: ‘x.x’ will match ‘xxx’ and also ‘xyx’. Special Sequences: d Matches any decimal digit; this is equivalent to the class [0-9].
  • 3. © Prof Mukesh N Tekwani, 2016 3 / 6 D Matches any non-digit character; this is equivalent to the class [^0-9]. s Matches any whitespace character. S Matches any non-whitespace character. 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_]. 3.3 The re package: search() and match() The re package provides two methods to perform queries on an input string. These methods are: re.search() and re.match() re.search() method: Syntax of search(): re.search(pattern, string) The description of parameters is as follows: Parameter Description pattern It is the regular expression to be matched string This is the string, which would be searched to match the pattern anywhere in the string. The re.search function returns a match object on success, none on failure. Program 1: RegEx1.py Write a program to search if a pattern 'aa[bc]*dd' appears in the line input by the user. import sys, re pat = re.compile('aa[bc]*dd') while 1: line = input('Enter a line ("q" to quit):') if line == 'q':
  • 4. © Prof Mukesh N Tekwani, 2016 4 / 6 break if pat.search(line): print ('matched:', line) else: print ('no match:', line) Analysis: 1. We import module re in order to use regular expressions. 2. re.compile() compiles a regular expression so that we can reuse the compiled regular expression without compiling it repeatedly. Output: Enter a line ("q" to quit):aabcdd matched: aabcdd Enter a line ("q" to quit):abcd no match: abcd Enter a line ("q" to quit):aacd no match: aacd Enter a line ("q" to quit):aadd matched: aadd Enter a line ("q" to quit):aabcbcdd matched: aabcbcdd Enter a line ("q" to quit):aabcdddd matched: aabcdddd Enter a line ("q" to quit):q >>> Program 2: RegEx2.py Write a program that searches for the occurrence of the pattern ‘A’ followed by a single digit, followed by the pattern ‘bb’. import sys, re pat = re.compile('A[0-9]bb') while 1: line = input('Enter a line ("q" to quit):') if line == 'q': break if pat.search(line): print ('matched:', line) else:
  • 5. © Prof Mukesh N Tekwani, 2016 5 / 6 print ('no match:', line) In the above program, search is used to search a string and match the first string from the left. search() searches for the pattern anywhere in the string. Output: Enter a line ("q" to quit):A65b no match: A65b Enter a line ("q" to quit):A65bb no match: A65bb Enter a line ("q" to quit):A6bb matched: A6bb Enter a line ("q" to quit):AA6bb matched: AA6bb Enter a line ("q" to quit):AA6bbc matched: AA6bbc Enter a line ("q" to quit):q >>> re.match() method: Syntax of search(): re.match(pattern, string) The description of parameters is as follows: Parameter Description pattern It is the regular expression to be matched string This is the string, which would be searched to match the pattern anywhere in the string. flags You can specify different flags using bitwise OR (|). The re.match function returns a match object on success, None on failure. We use group(num) or groups() function of match object to get matched expression. group(num=0) This method returns entire match (or specific subgroup num)
  • 6. © Prof Mukesh N Tekwani, 2016 6 / 6 groups() This method returns all matching subgroups in a tuple ** Example of using escape sequence: Start Python and type the following two lines. >>> name = 'AlbertnEinstein' >>> print(name) The output is as shown below. Note that the n character is a new line character. This character is treated as a single character. This character causes the remaining part to appear in the next line Output: Albert Einstein ** Raw Strings: Raw strings are strings with escape characters disabled. We have to add the character ‘r’ or ‘R’ as a prefix to our strings to make them raw strings. Modify the above example as follows: >>> name = r'AlbertnEinstein' >>> print (name) AlbertnEinstein >>> Note that the n character had no effect in this case. IMPORTANT QUESTIONS 1. What is a regular expression? Which module provides support for regular expressions? 2. What is meant by the following: Literal characters, concatenated patterns, alternate patterns, repeating and optional items, sets of characters. 3. What is a metacharacter? List the metacharacters used in Python. Explain the following metacharacters: [ and ], ^, and . 4. With an example, explain the search and match methods. 5. What is a raw string? Explain with a simple example.