+

Python Regex: re.search () VS re.findall ()

# Python program that demonstrates re.match ().

import re 

 
# Allows you to use a regular expression for date string matching
# as 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 & quot; ([a-zA-Z] +) (/ d +) & quot;

# matches pages o date.

 

# 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 " % < code class = "plain"> (match.group ( 0 )))

 

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

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. " )

Exit :

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

re. findall ()

Return 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.

Example :

# Python program for demonstrations
# find all ()

import re 

 
# An example of a text string where the regular expression
# 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) 

Output:

 [`123456789`,` 987654321`] 
Get Solution for free from DataCamp guru