Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python re.match() Method

Python re.match() Method

Python re Module Python re Module


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

- Type: string (str) - Description: the regular expression pattern to match. - Type: string (str) - Description: the string to match. - Type: integer (int, optional) - Description: regular expression flags.

Function description


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:

   

print

(

"Match succeeded:"

,

result.

group

(

)

)

   

print

(

"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:

   

print

(

"Match succeeded:"

,

result.

group

(

)

)

else

:

   

print

(

"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:

   

print

(

"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:

   

print

(

"Full match:"

,

result.

group

(

)

)

   

print

(

"Group 1:"

,

result.

group

(

1

)

)

   

print

(

"Group 2:"

,

result.

group

(

2

)

)

Expected output:

完整匹配: Hello World
第1组: Hello
第2组: World

Python re Module Python re Module