Open In App

Regular Expressions in Python – Set 2 (Search, Match and Find All)

Last Updated : 14 Dec, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Regular Expression in Python with Examples | Set 1
The module re provides support for regular expressions in Python. Below are main methods in this module.

Searching an occurrence of pattern 

re.search() : This method either returns None (if the pattern doesn’t match), or a re.MatchObject that contains information about the matching part of the string. This method stops after the first match, so this is best suited for testing a regular expression more than extracting data.

Python3




# A Python program to demonstrate working of re.match(). 
import re 
   
# Lets use a regular expression to match a date string 
# in the form of Month name followed by day number 
regex = r"([a-zA-Z]+) (\d+)"
   
match = re.search(regex, "I was born on June 24"
   
if match != None
   
    # We reach here when the expression "([a-zA-Z]+) (\d+)" 
    # matches the date string. 
   
    # This will print [14, 21), since it matches at index 14 
    # and ends at 21. 
    print ("Match at index %s, %s" % (match.start(), match.end())) 
   
    # We us group() method to get all the matches and 
    # captured groups. The groups contain the matched values. 
    # In particular: 
    # match.group(0) always returns the fully matched string 
    # match.group(1) match.group(2), ... return the capture 
    # groups in order from left to right in the input string 
    # match.group() is equivalent to match.group(0) 
   
    # So this will print "June 24" 
    print ("Full match: %s" % (match.group(0))) 
   
    # So this will print "June" 
    print ("Month: %s" % (match.group(1))) 
   
    # So this will print "24" 
    print ("Day: %s" % (match.group(2)))
   
else
    print ("The regex pattern does not match.")


Output : 

Match at index 14, 21
Full match: June 24
Month: June
Day: 24 

Matching a Pattern with Text 

re.match() : This function attempts to match pattern to whole string. The re.match function returns a match object on success, None on failure. 

re.match(pattern, string, flags=0)

pattern : Regular expression to be matched.
string : String where pattern is searched
flags : We can specify different flags 
        using bitwise OR (|). 

Python3




# A Python program to demonstrate working
# of re.match().
import re
    
# a sample function that uses regular expressions
# to find month and day of a date.
def findMonthAndDate(string):
        
    regex = r"([a-zA-Z]+) (\d+)"
    match = re.match(regex, string)
        
    if match == None
        print ("Not a valid date")
        return
    
    print ("Given Data: %s" % (match.group()))
    print ("Month: %s" % (match.group(1)))
    print ("Day: %s" % (match.group(2)))
    
        
# Driver Code
findMonthAndDate("Jun 24")
print("")
findMonthAndDate("I was born on June 24")


Output: 

Given Data: Jun 24
Month: Jun
Day: 24

Not a valid date

Finding all occurrences of a pattern 

re.findall() : Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found (Source : Python Docs). 

Python3




# A Python program to demonstrate working of
# findall()
import re
   
# A sample text string where regular expression 
# is searched.
string  = """Hello my Number is 123456789 and
             my friend's number is 987654321"""
   
# A sample regular expression to find digits.
regex = '\d+'            
   
match = re.findall(regex, string)
print(match)
   
# This example is contributed by Ayush Saluja.


Output : 

['123456789', '987654321']

Regular expression is a vast topic. It’s a complete library. Regular expressions can do a lot of stuff. You can Match, Search, Replace, Extract a lot of data. For example, below small code is so powerful that it can extract email address from a text. So we can make our own Web Crawlers and scrappers in python with easy.Look at the below regex. 

# extract all email addresses and add them into the resulting set
new_emails = set(re.findall(r"[a-z0-9\.\-+_]+@[a-z0-9\.\-+_]+\.[a-z]+", 
                           text, re.I))

We will soon be discussing more methods on regular expressions.

 



Similar Reads

Extracting email addresses using regular expressions in Python
Let suppose a situation in which you have to read some specific data like phone numbers, email addresses, dates, a collection of words etc. How can you do this in a very efficient manner?The Best way to do this by Regular Expression. Let take an example in which we have to find out only email from the given input by Regular Expression. Examples: In
3 min read
Python Flags to Tune the Behavior of Regular Expressions
Python offers some flags to modify the behavior of regular expression engines. Let's discuss them below: Case InsensitivityDot Matching NewlineMultiline ModeVerbose ModeDebug ModeCase Insensitivity The re.IGNORECASE allows the regular expression to become case-insensitive. Here, the match is returned based on the case of the provided string, not th
3 min read
Validating Bank Account Number Using Regular Expressions
A bank account number is a unique number that is assigned to the account holder after opening their account in any specific bank. In technical terms, we can consider the Bank account number as the Primary Key. A bank account number enables us to do debit, credit, and other transactions. As per RBI Guidelines, Bank Account Number has a unique struct
6 min read
Python | re.search() vs re.match()
Prerequisite: Regex in Python The re.search() and re.match() both are functions of re module in python. These functions are very efficient and fast for searching in strings. The function searches for some substring in a string and returns a match object if found, else it returns none. There is a difference between the use of both functions. Both re
2 min read
Python - Test rear digit match in all list elements
Sometimes we may face a problem in which we need to find a list if it contains numbers ending with the same digits. This particular utility has an application in day-day programming. Let’s discuss certain ways in which this task can be achieved. Method #1: Using list comprehension + map() We can approach this problem by converting the elements to t
6 min read
Find all the numbers in a string using regular expression in Python
Given a string str containing numbers and alphabets, the task is to find all the numbers in str using regular expression. Examples: Input: abcd11gdf15hnnn678hh4 Output: 11 15 678 4 Input: 1abcd133hhe0 Output: 1 133 0 Approach: The idea is to use Python re library to extract the sub-strings from the given string which match the pattern [0-9]+. This
1 min read
Python | Set 2 (Variables, Expressions, Conditions and Functions)
Introduction to Python has been dealt with in this article. Now, let us begin with learning python. Running your First Code in Python Python programs are not compiled, rather they are interpreted. Now, let us move to writing python code and running it. Please make sure that python is installed on the system you are working on. If it is not installe
3 min read
Set Matplotlib colorbar size to match graph
Colorbar size that match graph or image is required to get good visualize effect. This can be achieved using any one of following approaches. Use fraction parameter to match graph Fraction parameter in colorbar() is used to set the size of colorbar in Python. Using this we can match colorbar size to graph as: If vertical colorbar is used, then frac
4 min read
Python | Get match indices
Sometimes, while working with lists we need to handle two lists and search for the matches, and return just the indices of the match. Querying the whole list for this process is not feasible when the size of master list is very large, hence having just the match indices helps in this cause. Let's discuss certain ways in which this can be achieved.
4 min read
Python | Substring Key match in dictionary
Sometimes, while working with dictionaries, we might have a use case in which we are not known the exact keys we require but just a specific part of keys that we require to fetch. This kind of problem can arise in many applications. Let's discuss certain ways in which this problem can be solved. Method #1 : Using items() + list comprehension The co
9 min read
Article Tags :
Practice Tags :