Python re.match() Method
re.match() is a function in the Python re module used toMatch from the beginning of the stringa function for the pattern.
If the beginning of the string matches the specified regular expression, a match object is returned; otherwise None。
Word meaning: match means "to match".
Basic syntax and parameters
re.match() is a module-level function, called directly through the re module.
Syntax format
re.match(pattern, string, flags=0)
Parameter Description
- pattern:
- Type: string (str)
- Description: the regular expression pattern to match.
- string:
- Type: string (str)
- Description: the string to match.
- flags:
- Type: integer (int, optional)
- Description: regular expression flags.
Function description
- Return Value: If the beginning of the string matches, return a
matchobject; otherwise returnNone。 - Note:
re.match()Only matches from the beginning of the string; it does not scan the middle of the string.
Example
Let's master it through examples re.match() through a series of examples from simple to complex.
Example 1: basic usage - match at the beginning
Example
import
re
text
=
"Python is a powerful programming language"
Match "Python" from the beginning
result
=
re
.
match
(
r
'Python'
,
text
)
if
result:
(
"Match succeeded:"
,
result.
group
(
)
)
(
"Match position:"
,
result.
start
(
)
,
"-"
,
result.
end
(
)
)
Expected output:
匹配成功: Python
匹配位置: 0 - 6
Example 2: when the beginning does not match
Example
import
re
text
=
"I am Python"
Match "Python" from the beginning - this fails
result
=
re
.
match
(
r
'Python'
,
text
)
if
result:
(
"Match succeeded:"
,
result.
group
(
)
)
else
:
(
"Match failed: the string does not start with Python"
)
Expected output:
匹配失败: 字符串开头不是Python
Example 3: matching content following the start of the string
Example
import
re
text
=
"2024 is a special year"
Match a year format (4 digits)
result
=
re
.
match
(
r
'\d{4}'
,
text
)
if
result:
(
"Year matched:"
,
result.
group
(
)
)
Expected output:
匹配到年份: 2024
Example 4: use groups to extract data
Example
import
re
text
=
"Hello World"
Match "Hello" followed by a space and "World"
result
=
re
.
match
(
r
'(Hello) (World)'
,
text
)
if
result:
(
"Full match:"
,
result.
group
(
)
)
(
"Group 1:"
,
result.
group
(
1
)
)
(
"Group 2:"
,
result.
group
(
2
)
)
Expected output:
完整匹配: Hello World
第1组: Hello
第2组: World
Python re Module