The Python re.match() method is used to determine if the regular expression matches at the beginning of a string. It returns a match object if the pattern is found or 'None' otherwise.
Unlike the method re.search(), the re.match() only checks for a match at the beginning of the string. It is useful for validating input or extracting specific patterns at the start of a string.
This method takes a regular expression pattern and a string as arguments. If the pattern matches the beginning of the string it returns a match object containing information about the match such as the matched text and any captured groups.
SyntaxFollowing is the syntax and parameters of Python re.match() method −
re.match(pattern, string, flags=0)Parameters
Following are the parameter of the python re.match() method −
This method returns the match object if the pattern is found in the string otherwise it returns None.
Example 1Following is the basic example of using the re.match() method. In this example the pattern 'hello' is matched against the beginning of the string 'hello, world!' −
import re result = re.match(r'hello', 'hello, world!') if result: print("Pattern found:", result.group()) else: print("Pattern not found")Output
Pattern found: helloExample 2
Here in this example the pattern '\d+-\d+-\d+' is matched against the beginning of the string and groups are used to extract the date components −
import re result = re.match(r'(\d+)-(\d+)-(\d+)', '2022-01-01: New Year') if result: print("Pattern found:", result.group())Output
Pattern found: 2022-01-01Example 3
Here in this example named groups are used to extract the first and last names from the beginning of the string −
import re result = re.match(r'(?P<first>\w+) (?P<last>\w+)', 'John Doe') if result: print("First Name:", result.group('first')) print("Last Name:", result.group('last'))Output
First Name: John Last Name: Doe
python_modules.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4