為什麼我們在 Python 正則表示式中使用問號字面量?


簡介

問號使 正則表示式 中的前一個標記可選。例如:colou?r 既可以匹配 colour,也可以匹配 colour。問號被稱為量詞。

您可以透過將多個標記組合在括號中並在最後一個括號組之後新增問號來使多個標記可選。例如 Nov(ember)? 匹配 Nov 和 November。

使用多個問號,您可以建立一個匹配各種選項的正則表示式。Feb(ruary)? 23(rd)? 匹配 February 23rd、February 23、Feb 23rd 和 Feb 23。

花括號也可以用來使某些內容可選。colou?r 的等價形式是 colou{0,1}r。POSIX BRE 和 GNU BRE 都不相容。花括號需要反斜槓來傳達以下風格的特定含義:colou\{0,1\}r

重要的正則表示式概念:貪婪

本課程介紹的第一個貪婪元字元是問號。對於問號,正則表示式引擎有兩個選擇:要麼嘗試匹配問號所指的部分,要麼不嘗試匹配它。引擎總是嘗試匹配該部分。除非這會導致整個正則表示式失敗,否則引擎不會嘗試忽略問號適用的部分。

因此,當正則表示式 Feb 23(rd)? 應用於文字 Today is Feb 23, 2003 時,匹配結果始終是 Feb 23rd,而不是 Feb 23。透過在第一個問號之後再新增一個問號,您可以使問號變為懶惰(即關閉貪婪)。

使用的語法

re.findall(): The re.findall(pattern, string) method finds all pattern
occurrences in the string and returns a list of all matching substrings.

The first parameter is the regular expression pattern "aa[cde]?". The string to
be checked for patterns is the second parameter. Simply put, you're looking for
patterns that begin with two 'a' characters and one optional character that
might be a 'c', 'd', or 'e.

示例

#importing re functions import re #findall function to result1 = re.findall('aa[cde]?', 'aacde aa aadcde') #The re.findall(pattern, string) method finds all pattern occurrences in the string and returns a list of all matching substrings. result2 = re.findall('aa?', 'accccacccac') result3 = re.findall('[cd]?[cde]?', 'ccc dd ee') #printing the results print(result1) print(result2) print(result3)

輸出

['aac', 'aa', 'aad']
['a', 'a', 'a']
['cc', 'c', '', 'dd', '', 'e', 'e', '']

程式碼解釋

findall() 方法返回三個匹配的子字串 -

首先,模式與字串 "aac" 匹配。在 Python 消耗匹配的子字串後,剩餘的字串為 "de aa aadcde"。此外,字串 "aa" 匹配模式。Python 消耗它,只留下子字串 "aadcde"。第三,最後一個子字串中的模式與字串 "aad" 匹配。剩下的就是 "cde",它不再有匹配的子字串。

深入正則表示式引擎

讓我們將正則表示式 colou?r 應用於字串 The colonel likes the colour green。

正則表示式中的第一個標記是字面量 c。它在 colonel 中的第一個 c 處首次成功匹配。引擎繼續執行,發現 l 匹配 l,另一個 o 匹配 o,o 匹配 o。然後引擎檢查 u 和 n 是否相等。它失敗了。但是,問號指示正則表示式引擎允許缺少字元 u。因此,引擎繼續處理下一個正則表示式標記 r。但是,這也無法匹配 n。現在,引擎只能得出結論,從 colonel 中的 c 開始的整個正則表示式無法匹配。為了將 c 與 colonel 中的第一個 o 進行匹配,引擎重新開始。

在一系列失敗之後,o、l 和 o 匹配後續字元,c 匹配 colour 中的 c。引擎現在檢查 u 和 r 是否匹配。它失敗了。再次,沒有問題。由於問號的存在,引擎可以繼續處理 r。引擎表示正則表示式在我們的文字中成功匹配了 colour,因為它匹配了 r。

結論

當應用於正則表示式 A 時,Python 的 A? 量詞匹配 A 的零個或一個例項。例如,正則表示式 "hey?" 匹配字串 "he" 和 "hey",但不匹配空字串 "."。這是因為? 量詞僅應用於它之前的正則表示式 'y',而不是整個正則表示式 ', hey'。

更新於: 2023-11-02

3K+ 瀏覽量

開啟你的 職業生涯

完成課程獲得認證

開始學習
廣告

© . All rights reserved.