Python - AI 助手

Python re.match() 方法



Python 的 re.match() 方法用於判斷正則表示式是否匹配字串的開頭。如果找到匹配項,則返回一個匹配物件;否則返回 'None'。

re.search() 方法不同,re.match() 僅檢查字串開頭的匹配項。它適用於驗證輸入或提取字串開頭特定模式。

此方法將正則表示式模式和字串作為引數。如果模式與字串開頭匹配,則返回一個匹配物件,其中包含有關匹配的資訊,例如匹配的文字和任何捕獲的組。

語法

以下是 Python re.match() 方法的語法和引數:

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

引數

以下是 python re.match() 方法的引數:

  • pattern: 要搜尋的正則表示式模式。
  • string: 要在其內搜尋的輸入字串。
  • flags(可選): 這些標誌修改匹配的行為。可以使用按位或 (|) 組合這些標誌。

返回值

如果在字串中找到模式,則此方法返回匹配物件;否則返回 None。

示例 1

以下是使用 re.match() 方法的基本示例。在此示例中,模式 'hello' 與字串 'hello, world!' 的開頭匹配:

import re

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

輸出

Pattern found: hello

示例 2

在此示例中,模式 '\d+-\d+-\d+' 與字串的開頭匹配,並使用組提取日期元件:

import re

result = re.match(r'(\d+)-(\d+)-(\d+)', '2022-01-01: New Year')
if result:
    print("Pattern found:", result.group())  

輸出

Pattern found: 2022-01-01

示例 3

在此示例中,命名組用於從字串的開頭提取名字和姓氏:

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'))    

輸出

First Name: John
Last Name: Doe
python_modules.htm
廣告