Submit Search
Upload
Python - Regular Expressions
•
Download as DOCX, PDF
•
1 like
•
1,250 views
M
Mukesh Tekwani
Follow
Regular expressions, also known as regex, in Python
Read less
Read more
Software
Report
Share
Report
Share
1 of 6
Download now
Recommended
Python (regular expression)
Python (regular expression)
Chirag Shetty
Python advanced 2. regular expression in python
Python advanced 2. regular expression in python
John(Qiang) Zhang
Python : Regular expressions
Python : Regular expressions
Emertxe Information Technologies Pvt Ltd
Adv. python regular expression by Rj
Adv. python regular expression by Rj
Shree M.L.Kakadiya MCA mahila college, Amreli
Regular expressions in Python
Regular expressions in Python
Sujith Kumar
Processing Regex Python
Processing Regex Python
primeteacher32
Java: Regular Expression
Java: Regular Expression
Masudul Haque
16 Java Regex
16 Java Regex
wayn
Recommended
Python (regular expression)
Python (regular expression)
Chirag Shetty
Python advanced 2. regular expression in python
Python advanced 2. regular expression in python
John(Qiang) Zhang
Python : Regular expressions
Python : Regular expressions
Emertxe Information Technologies Pvt Ltd
Adv. python regular expression by Rj
Adv. python regular expression by Rj
Shree M.L.Kakadiya MCA mahila college, Amreli
Regular expressions in Python
Regular expressions in Python
Sujith Kumar
Processing Regex Python
Processing Regex Python
primeteacher32
Java: Regular Expression
Java: Regular Expression
Masudul Haque
16 Java Regex
16 Java Regex
wayn
Regular expressions
Regular expressions
Thomas Langston
Python- Regular expression
Python- Regular expression
Megha V
Python Programming - XI. String Manipulation and Regular Expressions
Python Programming - XI. String Manipulation and Regular Expressions
Ranel Padon
Python programming : Strings
Python programming : Strings
Emertxe Information Technologies Pvt Ltd
Strings in Python
Strings in Python
nitamhaske
Python - Lecture 7
Python - Lecture 7
Ravi Kiran Khareedi
Regular Expression
Regular Expression
Bharat17485
Regular Expressions
Regular Expressions
Satya Narayana
Textpad and Regular Expressions
Textpad and Regular Expressions
OCSI
Java chapter 6 - Arrays -syntax and use
Java chapter 6 - Arrays -syntax and use
Mukesh Tekwani
Data Structures in Python
Data Structures in Python
Devashish Kumar
Python strings
Python strings
Mohammed Sikander
Php String And Regular Expressions
Php String And Regular Expressions
mussawir20
Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm
KristinaBorooah
Regular Expression
Regular Expression
Mahzad Zahedi
Andrei's Regex Clinic
Andrei's Regex Clinic
Andrei Zmievski
Finaal application on regular expression
Finaal application on regular expression
Gagan019
Strings in python
Strings in python
Prabhakaran V M
Regular Expressions in PHP
Regular Expressions in PHP
Andrew Kandels
Chapter 14 strings
Chapter 14 strings
Praveen M Jigajinni
Html graphics
Html graphics
Mukesh Tekwani
Data Link Layer
Data Link Layer
Mukesh Tekwani
More Related Content
What's hot
Regular expressions
Regular expressions
Thomas Langston
Python- Regular expression
Python- Regular expression
Megha V
Python Programming - XI. String Manipulation and Regular Expressions
Python Programming - XI. String Manipulation and Regular Expressions
Ranel Padon
Python programming : Strings
Python programming : Strings
Emertxe Information Technologies Pvt Ltd
Strings in Python
Strings in Python
nitamhaske
Python - Lecture 7
Python - Lecture 7
Ravi Kiran Khareedi
Regular Expression
Regular Expression
Bharat17485
Regular Expressions
Regular Expressions
Satya Narayana
Textpad and Regular Expressions
Textpad and Regular Expressions
OCSI
Java chapter 6 - Arrays -syntax and use
Java chapter 6 - Arrays -syntax and use
Mukesh Tekwani
Data Structures in Python
Data Structures in Python
Devashish Kumar
Python strings
Python strings
Mohammed Sikander
Php String And Regular Expressions
Php String And Regular Expressions
mussawir20
Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm
KristinaBorooah
Regular Expression
Regular Expression
Mahzad Zahedi
Andrei's Regex Clinic
Andrei's Regex Clinic
Andrei Zmievski
Finaal application on regular expression
Finaal application on regular expression
Gagan019
Strings in python
Strings in python
Prabhakaran V M
Regular Expressions in PHP
Regular Expressions in PHP
Andrew Kandels
Chapter 14 strings
Chapter 14 strings
Praveen M Jigajinni
What's hot
(20)
Regular expressions
Regular expressions
Python- Regular expression
Python- Regular expression
Python Programming - XI. String Manipulation and Regular Expressions
Python Programming - XI. String Manipulation and Regular Expressions
Python programming : Strings
Python programming : Strings
Strings in Python
Strings in Python
Python - Lecture 7
Python - Lecture 7
Regular Expression
Regular Expression
Regular Expressions
Regular Expressions
Textpad and Regular Expressions
Textpad and Regular Expressions
Java chapter 6 - Arrays -syntax and use
Java chapter 6 - Arrays -syntax and use
Data Structures in Python
Data Structures in Python
Python strings
Python strings
Php String And Regular Expressions
Php String And Regular Expressions
Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm
Regular Expression
Regular Expression
Andrei's Regex Clinic
Andrei's Regex Clinic
Finaal application on regular expression
Finaal application on regular expression
Strings in python
Strings in python
Regular Expressions in PHP
Regular Expressions in PHP
Chapter 14 strings
Chapter 14 strings
Viewers also liked
Html graphics
Html graphics
Mukesh Tekwani
Data Link Layer
Data Link Layer
Mukesh Tekwani
Html tables examples
Html tables examples
Mukesh Tekwani
Java chapter 5
Java chapter 5
Mukesh Tekwani
Java chapter 3
Java chapter 3
Mukesh Tekwani
Java chapter 1
Java chapter 1
Mukesh Tekwani
Python reading and writing files
Python reading and writing files
Mukesh Tekwani
Jdbc 1
Jdbc 1
Mukesh Tekwani
Digital signal and image processing FAQ
Digital signal and image processing FAQ
Mukesh Tekwani
Java misc1
Java misc1
Mukesh Tekwani
Java swing 1
Java swing 1
Mukesh Tekwani
Java chapter 3 - OOPs concepts
Java chapter 3 - OOPs concepts
Mukesh Tekwani
Java 1-contd
Java 1-contd
Mukesh Tekwani
Phases of the Compiler - Systems Programming
Phases of the Compiler - Systems Programming
Mukesh Tekwani
Data communications ch 1
Data communications ch 1
Mukesh Tekwani
Chap 3 data and signals
Chap 3 data and signals
Mukesh Tekwani
Chapter 26 - Remote Logging, Electronic Mail & File Transfer
Chapter 26 - Remote Logging, Electronic Mail & File Transfer
Wayne Jones Jnr
Introduction to systems programming
Introduction to systems programming
Mukesh Tekwani
Viewers also liked
(18)
Html graphics
Html graphics
Data Link Layer
Data Link Layer
Html tables examples
Html tables examples
Java chapter 5
Java chapter 5
Java chapter 3
Java chapter 3
Java chapter 1
Java chapter 1
Python reading and writing files
Python reading and writing files
Jdbc 1
Jdbc 1
Digital signal and image processing FAQ
Digital signal and image processing FAQ
Java misc1
Java misc1
Java swing 1
Java swing 1
Java chapter 3 - OOPs concepts
Java chapter 3 - OOPs concepts
Java 1-contd
Java 1-contd
Phases of the Compiler - Systems Programming
Phases of the Compiler - Systems Programming
Data communications ch 1
Data communications ch 1
Chap 3 data and signals
Chap 3 data and signals
Chapter 26 - Remote Logging, Electronic Mail & File Transfer
Chapter 26 - Remote Logging, Electronic Mail & File Transfer
Introduction to systems programming
Introduction to systems programming
Similar to Python - Regular Expressions
Regular_Expressions.pptx
Regular_Expressions.pptx
DurgaNayak4
Python regular expressions
Python regular expressions
Krishna Nanda
Regular expressions
Regular expressions
Raj Gupta
Maxbox starter20
Maxbox starter20
Max Kleiner
Regular expressions in oracle
Regular expressions in oracle
Logan Palanisamy
Regular expressions
Regular expressions
Raghu nath
Module 3 - Regular Expressions, Dictionaries.pdf
Module 3 - Regular Expressions, Dictionaries.pdf
GaneshRaghu4
Python data handling
Python data handling
Prof. Dr. K. Adisesha
2.regular expressions
2.regular expressions
Praveen Gorantla
unit-4 regular expression.pptx
unit-4 regular expression.pptx
PadreBhoj
Don't Fear the Regex - CapitalCamp/GovDays 2014
Don't Fear the Regex - CapitalCamp/GovDays 2014
Sandy Smith
regular-expression.pdf
regular-expression.pdf
DarellMuchoko
Regex lecture
Regex lecture
Jun Shimizu
Bioinformatica 06-10-2011-p2 introduction
Bioinformatica 06-10-2011-p2 introduction
Prof. Wim Van Criekinge
Chapter 3: Introduction to Regular Expression
Chapter 3: Introduction to Regular Expression
azzamhadeel89
14 ruby strings
14 ruby strings
Walker Maidana
Strings,patterns and regular expressions in perl
Strings,patterns and regular expressions in perl
sana mateen
Unit 1-strings,patterns and regular expressions
Unit 1-strings,patterns and regular expressions
sana mateen
String interpolation
String interpolation
Knoldus Inc.
Java căn bản - Chapter9
Java căn bản - Chapter9
Vince Vo
Similar to Python - Regular Expressions
(20)
Regular_Expressions.pptx
Regular_Expressions.pptx
Python regular expressions
Python regular expressions
Regular expressions
Regular expressions
Maxbox starter20
Maxbox starter20
Regular expressions in oracle
Regular expressions in oracle
Regular expressions
Regular expressions
Module 3 - Regular Expressions, Dictionaries.pdf
Module 3 - Regular Expressions, Dictionaries.pdf
Python data handling
Python data handling
2.regular expressions
2.regular expressions
unit-4 regular expression.pptx
unit-4 regular expression.pptx
Don't Fear the Regex - CapitalCamp/GovDays 2014
Don't Fear the Regex - CapitalCamp/GovDays 2014
regular-expression.pdf
regular-expression.pdf
Regex lecture
Regex lecture
Bioinformatica 06-10-2011-p2 introduction
Bioinformatica 06-10-2011-p2 introduction
Chapter 3: Introduction to Regular Expression
Chapter 3: Introduction to Regular Expression
14 ruby strings
14 ruby strings
Strings,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 expressions
String interpolation
String interpolation
Java 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 Channel
Mukesh Tekwani
The Elphinstonian 1988-College Building Centenary Number (2).pdf
The Elphinstonian 1988-College Building Centenary Number (2).pdf
Mukesh Tekwani
Circular motion
Circular motion
Mukesh Tekwani
Gravitation
Gravitation
Mukesh Tekwani
ISCE-Class 12-Question Bank - Electrostatics - Physics
ISCE-Class 12-Question Bank - Electrostatics - Physics
Mukesh Tekwani
Hexadecimal to binary conversion
Hexadecimal to binary conversion
Mukesh Tekwani
Hexadecimal to decimal conversion
Hexadecimal to decimal conversion
Mukesh Tekwani
Hexadecimal to octal conversion
Hexadecimal to octal conversion
Mukesh Tekwani
Gray code to binary conversion
Gray code to binary conversion
Mukesh Tekwani
What is Gray Code?
What is Gray Code?
Mukesh Tekwani
Decimal to Binary conversion
Decimal to Binary conversion
Mukesh Tekwani
Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21
Mukesh Tekwani
Refraction and dispersion of light through a prism
Refraction and dispersion of light through a prism
Mukesh Tekwani
Refraction of light at a plane surface
Refraction of light at a plane surface
Mukesh Tekwani
Spherical mirrors
Spherical mirrors
Mukesh Tekwani
Atom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atom
Mukesh Tekwani
Refraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lenses
Mukesh Tekwani
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
Mukesh Tekwani
Cyber Laws
Cyber Laws
Mukesh Tekwani
XML
XML
Mukesh Tekwani
More from Mukesh Tekwani
(20)
Computer 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).pdf
Circular motion
Circular motion
Gravitation
Gravitation
ISCE-Class 12-Question Bank - Electrostatics - Physics
ISCE-Class 12-Question Bank - Electrostatics - Physics
Hexadecimal to binary conversion
Hexadecimal to binary conversion
Hexadecimal to decimal conversion
Hexadecimal to decimal conversion
Hexadecimal to octal conversion
Hexadecimal to octal conversion
Gray code to binary conversion
Gray code to binary conversion
What is Gray Code?
What is Gray Code?
Decimal to Binary conversion
Decimal to Binary conversion
Video 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 prism
Refraction of light at a plane surface
Refraction of light at a plane surface
Spherical mirrors
Spherical mirrors
Atom, 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 lenses
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
Cyber Laws
Cyber Laws
XML
XML
Recently uploaded
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
kalichargn70th171
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
kalichargn70th171
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.ppt
kotipi9215
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 Delhi Whatsup 9873940964 Enjoy Unlimited Pleasure
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
kaushalgiri8080
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 Systems
JheuzeDellosa
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
Tier1 app
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
joe51371421
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
Wave PLM
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.pdf
Wave PLM
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
bodapatigopi8531
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software Solutions
Mehedi Hasan Shohan
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.pdf
Power Karaoke
EY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
Neo4j
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
Ortus Solutions, Corp
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.pdf
The 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...
chapter--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...
Project 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...
What is Binary Language? Computer Number Systems
What is Binary Language? Computer Number Systems
KnowAPIs-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.pdf
What 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)
5 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.pptx
XpertSolvers: 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 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 Sustainability
BATTLEFIELD 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...
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.
Download now