re.match()
this function tries to match pattern with all of string. re.match()
function returns the match object into success without failure.
re.match(pattern, string, flag=0)
# A Python program to demonstrate working of re.match().
import re
# Let's 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 use 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.")
Match at index 14, 21
Full match: June 24
Month: June
Day: 24
# 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 ("Dat: %s" % (match.group(2)))
# Driver Code
findMonthAndDate("Jun 24")
print("")
findMonthAndDate("I was born on June 24")
Given Data: Jun 24
Month: Jun
Dat: 24
Not a valid date
Search
# A Python program to demonstrate working of re.match().
import re
# Let's 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
print("Match at index %s, %s" % (match.start(), match.end()))
print("Full match: %s" % (match.group(0)))
print("Month: %s" % (match.group(1)))
print("Day: %s" % (match.group(2)))
else:
print("The regex pattern does not match.")
Match
# 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 ("Dat: %s" % (match.group(2)))
# Driver Code
findMonthAndDate("Jun 24")
print("")
findMonthAndDate("I was born on June 24")