Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python re.match() method



The Pythonre.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 methodre.search(), there.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.

Syntax

Following is the syntax and parameters of Pythonre.match() method −

re.match(pattern, string, flags=0)

Parameters

Following are the parameter of the pythonre.match() method −

  • pattern: The regular expression pattern to search for.
  • string: The input string to search within.
  • flags(optional): These flags modify the behavior of the match. These flags can be combined using bit-wise OR (|).

Return value

This method returns the match object if the pattern is found in the string otherwise it returns None.

Example 1

Following is the basic example of using there.match() method. In this example the pattern 'hello' is matched against the beginning of the string 'hello, world!' −

import reresult = re.match(r'hello', 'hello, world!')if result:    print("Pattern found:", result.group())  else:    print("Pattern not found")

Output

Pattern found: hello

Example 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 reresult = re.match(r'(\d+)-(\d+)-(\d+)', '2022-01-01: New Year')if result:    print("Pattern found:", result.group())

Output

Pattern found: 2022-01-01

Example 3

Here in this example named groups are used to extract the first and last names from the beginning of the string −

import reresult = 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: JohnLast Name: Doe
python_modules.htm
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp