Change language

Regular Expressions in Python | Set 2 (search, match and find all)

| | |

The re module provides regular expression support in Python. The following are the main methods in this module.

Search for occurrence of a pattern

re.search (): This the method either returns None (if the pattern does not match) or re.MatchObject, which contains information about the matching part of the string. This method stops after the first match, so it’s better for checking regular expressions than for extracting data.

# Python program to demonstrate how it works re.match ( ).

import re

 
# Use a regular expression to match the date string
# as month name followed by the 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 & quot; ([a-zA-Z] +) (/ d +) & quot;

  # matches the date string.

 

# This will print [14, 21) since it is at index 14

# and ends at 21.

print "Match at index% s,% s" % (match.start (), match.end ())

 

# We use the group () method to get all matches and

# captured groups. The groups contain matching values.

# Especially:

# match.group (0) always returns an exact match

  # match.group (1) match.group (2), ... return capture

# groups in order from left to right in the input line

# match.group () is equivalent to match.group (0)

 

# This will print June 24

print " Full match:% s " % (match.gr oup ( 0 ))

 

# This will print June

print "Month:% s" % (match.group ( 1 ))

 

# So this will print & quot; 24 & quot;

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 

Template match with text

re.match (): This function tries to match a pattern against an entire string. The re.match function returns a match object on success, None on error.

 re.match (pattern, string, flags = 0) pattern: Regular expression to be matched. string: String where p attern is searched flags: We can specify different flags using bitwise OR (|). 

# Python program to demonstrate how it works
# re.match ().

import re

 
# example of a function that uses regular expressions
# find the 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" )

Find all occurrences of a pattern

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

# Python program to demonstrate how it works
# find all ()

import re

 
# An example of a text string where the regular expression
# is searched.

string  = & quot; & quot; & quot; Hello my number is 123456789 and

my friend’s number is 987654321 & quot; & quot; & quot;

 
# An example of a regular expression for finding numbers.

regex = ’d +’  

 

match = re.findall (regex, string)

print ( match)

 
# This example is provided by Ayush Saluja.

Output:

 [’123456789’,’ 987654321’ ] 

Regular expression — extensive topic. This is a complete library. Regular expressions can do a lot. You can match, search, replace, extract a lot of data. For example, below is a little code so powerful that it can extract an email address from text. So we can make our own web crawlers and scrapers in python with easy.Look 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 .- + _] +. [az] +", text, re.I)) 

We are coming soon we’ll discuss more methods for regular expressions.

This article contributed by Shwetanshu Rohatgi . If you like Python.Engineering and would like to contribute, you can also write an article and mail it to [email protected] See your article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you’d like to share more information on the topic under discussion

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News


Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method