× Python Introduction What is Python Python Features Python History Python Applications Python Install Python Path Python Example Execute Python Keywords Constant Variable Statements & Comments Python I/O and Import Operators UnaryBinaryTernary Unary Operators Unary Minus Binary Operators Arithmetic Operators Assignment Operators Relational Operators Logicaloperators Bitwise Operator Ternary Operators Control Statements in Python conditonal Statements IF if else Else If Nested if Switch For loop Nested For Loop While Loop Nested while Loop Unconditonal Statemets Continue Break Pass FUNCTIONS Python Function Function Argument Python Recursion Anonymous Function Python Modules NATIVE DATATYPES Python List Python Numbers Python Tuple Python String Python Set Python Dictionary OOPS PRINCIPALS Encapsulation Class Variable Method Object Or Instance CreationMethod Calling OOPS Syntax And Explanation DATA ABSTRACTION Constructor Inheritance 1.Single or simple Inheritance 2.Multilevel Inheritance 3.Hierarchical Inheritance 4.Multiple Inheritance 5.Hybrid Inheritance Operator Overloading File Operation Python Directory Python Exception Python - Multithreading Python - Database Access Python - CGI Python - Reg Exp Python - Date Python - XML Processing Python - GUI
  • iconJava Online Training In Andhra Pradesh and Telangana
  • icon9010519704

Opening Hours :7AM to 9PM

Python Regular Expression


A RegEx, or Regular Expression, is a sequence of characters that forms a search pattern.
RegEx can be used to check if a string contains the specified search pattern.
RegEx Module
Python has a built-in package called re, which can be used to work with Regular Expressions. Import the re module:


import re
               

RegEx in Python
When you have imported the re module, you can start using regular expressions:
Example
Search the string to see if it starts with "The" and ends with "Germany":
import re
def myfun():
    #Check if the string starts with "The" and ends with "Germany":
    
    txt = "The rain in Germany"
    x = re.search("^The.*Germany$", txt)
    if x:
      print("YES! We have a match!")
    else:
      print("No match")


if __name__=="__main__":
    myfun()
Output:
RegEx Functions
The re module offers a set of functions that allows us to search a string for a match:
Function Description
findall Returns a list containing all matches
search Returns a Match object if there is a match anywhere in the string
split Returns a list where the string has been split at each match
sub Replaces one or many matches with a string
The findall() Function Example #1
The findall() function returns a list containing all matches. Example Print a list of all matches:
import re
def myfun():
    #Return a list containing every occurrence of "ni":

    txt = "The raining in Germani"
    x = re.findall("ni", txt)
    print(x)

if __name__=="__main__":
    myfun()
    
The list contains the matches in the order they are found.
If no matches are found, an empty list is returned:
Output:
The findall() Function Example #2
Return an empty list if no match was found:
import re
def myfun():
    #Return a list containing every occurrence of "pi":

    txt = "The raining in Germani"
    x = re.findall("pi", txt)
    print(x)

if __name__=="__main__":
    myfun()
Output:
The search() Function
The search() function searches the string for a match, and returns a Match object if there is a match.
If there is more than one match, only the first occurrence of the match will be returned:
Example Search for the first white-space character in the string:
import re
def myfun():
    txt = "The rain in Germany"
    x = re.search("\s", txt)
    print("The first white-space character is located in position:", x.start()) 

if __name__=="__main__":
    myfun()
If no matches are found, the value None is returned:
Output:
The search() Function- Make a search that returns no match:
import re
def myfun():
    
    txt = "The rain in Germany"
    x = re.search("sateesh", txt)
    print(x)


if __name__=="__main__":
    myfun()
Output:
The split() Function
The split() function returns a list where the string has been split at each match:

Example
Split at each white-space character:
import re
def myfun():
    #Split the string at every white-space character:
    txt = "The rain in Germany"
    x = re.split("\s", txt)
    print(x)

if __name__=="__main__":
    myfun()
    
You can control the number of occurrences by specifying the maxsplit parameter:
Output:
Split the string only at the first occurrence: Example #2
import re
def myfun():
    #Split the string at the first white-space character:
    txt = "The rain in Spain"
    x = re.split("\s", txt, 1)
    print(x)

if __name__=="__main__":
    myfun()
Output:
The sub() Function
The sub() function replaces the matches with the text of your choice:
Example
Replace every white-space character with the number 9:
 import re
def myfun():
    #Replace all white-space characters with the digit "24":
    
    txt = "The rain in Spain"
    x = re.sub("\s", "24", txt)
    print(x)

if __name__=="__main__":
    myfun()
Output:
Example #2 Replace the first 2 occurrences:
You can control the number of replacements by specifying the count parameter:
import re
def myfun():
    #Replace the first two occurrences of a white-space character with the digit 24:
    
    txt = "The rain in Germany"
    x = re.sub("\s", "24", txt, 2)
    print(x)

if __name__=="__main__":
    myfun()
Output: