Python - AI 助手

Python re.fullmatch() 方法



Python 的re.fullmatch()方法用於檢查整個字串是否與給定的正則表示式模式匹配。

與只匹配字串開頭的re.match()方法不同,re.fullmatch()方法確保模式跨越整個字串。如果模式完全匹配,則返回一個匹配物件;否則返回 None。

當我們需要驗證字串是否完全符合特定格式時,此方法非常有用。

語法

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

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

引數

以下是 Python re.fullmatch() 方法的引數:

  • pattern: 要匹配的正則表示式模式。
  • string: 要根據模式進行匹配的字串。
  • flags(可選): 這些標誌修改匹配行為

返回值

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

示例 1

以下是使用re.fullmatch()方法的基本示例。在此示例中,模式 '\d+' 匹配一個或多個數字,它完全匹配整個字串 '123456':

import re

result = re.fullmatch(r'\d+', '123456')
if result:
    print("Full match found:", result.group())  

輸出

Full match found: 123456

示例 2

在此示例中,模式 '\w+' 匹配一個或多個字母數字字元,它完全匹配字串 'abc123':

import re
result = re.fullmatch(r'\w+', 'abc123')
if result:
    print("Full match found:", result.group())  

輸出

Full match found: abc123

示例 3

在此示例中,我們使用re.IGNORECASE標誌使模式不區分大小寫,允許 'hello' 完全匹配 'HELLO':

import re

result = re.fullmatch(r'hello', 'HELLO', re.IGNORECASE)
if result:
    print("Full match found:", result.group()) 

輸出

Full match found: HELLO

示例 4

下面的示例檢查字串是否完全匹配:

import re

result = re.fullmatch(r'\d+', '123abc')
if result:
    print("Full match found:", result.group())
else:
    print("No full match found")  

輸出

No full match found
python_modules.htm
廣告