[Python] re.match

re.match()

How did I encounter this?

As a temporary feature, the server asks for user inputs for the purchase date. This value should follow a specific pattern to be processed. I used regex pattern check to validate the pattern.

Syntax

re.match(target_str, regex_pattern)

re.match() returns True if the target string matches the provided regex pattern.
The following is the example of using re.match()

import re

date_input = input('please enter a date in the format yyyy-mm-dd: ')

date_regex = r'^\d{4}-\d{2}-\d{2}$'

if re.match(date_input, date_regex):
   print('format matched')
else:
   print('format not matched')


Comments