如何在 Python 正則表示式中獲取真/假值?


**'re'** 模組在使用 Python 的正則表示式 (regex) 時提供了工具,它允許我們在字串中搜索任何特定的模式。

使用 're' 模組,我們可以利用例如 .match().search() 等函式從正則表示式中獲取 **True** 或 **False**。如果未檢測到任何模式,則此函式返回 'None',如果檢測到模式,則返回匹配物件。從 Python 正則表示式中獲取真/假值的一些常用方法如下:

  • 're.match()':檢查模式是否與字串的開頭匹配。

  • 're.search()':此函式掃描整個字串以查詢模式的第一次出現。

  • 're.fullmatch()':檢查整個字串是否完全匹配模式並返回匹配物件。

使用 're.match()'

透過使用 **'re.match()'**,我們可以檢查正則表示式或模式是否與給定字串的開頭匹配。如果模式與字串的開頭匹配,則返回匹配物件,否則返回 **'None'**。

示例

在下面的示例程式碼中,**"^hello"** 是模式,其中 ' ^ ' 定義字串開頭的位 置。**'bool()'** 在模式中存在匹配時評估為 **'True'**,否則在模式不匹配時返回 **'False'**。

import re

pattern = r"^hi"
text = "hello world"

match = re.match(pattern, text)

# Evaluates to True if there's a match
is_match = bool(match)  

print(is_match)

輸出

False

使用 're.search()'

要查詢模式的第一次出現,此 **'re.search()'** 方法會掃描整個字串,如果在字串中的任何位置找到模式,則返回匹配物件。

示例

在下面的程式碼中,單詞 **'world'** 是我們要搜尋的模式。字串 'hello world' 包含 'world' 作為其一部分,**'re.search()'** 在 **'text'** 中找到 'world' 並返回匹配物件。

import re

pattern = r"world"
text = "hello world"

match = re.search(pattern, text)

# Evaluates to True if there's a match
is_match = bool(match)  

print(is_match)  

輸出

True

使用 're.fullmatch()'

此方法 **'re.fullmatch()'** 檢查整個字串是否完全匹配給定模式。

示例

在下面,字串和模式都是 **'hello world'**,沒有其他字元。因此,**'re.fullmatch()'** 找到完全匹配並返回匹配物件。

import re

pattern = r"hello world"
text = "hello world"

match = re.fullmatch(pattern, text)

# Evaluates to True if there's a match
is_match = bool(match) 

print(is_match) 

輸出

True

更新於: 2024年10月14日

4K+ 閱讀量

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.