一、$符號概述
在Python正則表達式中,$符號表示字元串的結尾。如果直接將$符號放在正則表達式模式的末尾,則匹配的字元串必須以該模式結束。舉個例子,表達式”hello$”將只會匹配以”hello”結尾的字元串,而不是包含”hello”的所有字元串。
除了在正則表達式模式末尾使用$符號之外,還可以在模式中使用$n(1 ≤ n ≤ 99)表示第n個捕獲組的內容,這種用法將在下面的小節中詳細講述。
二、$符號的用法示例
下面的代碼展示了如何在Python中使用$符號。具體來說,它首先使用re模塊中的compile函數編譯了兩個正則表達式模式:第一個模式僅匹配以”hello”結尾的字元串,第二個模式則要求字元串以數字結尾。然後,使用match函數對這兩個模式進行匹配,輸出匹配結果。
import re patterns = [r"hello$", r"\d$"] strings = ["world hello", "python38"] for pattern in patterns: regex = re.compile(pattern) for string in strings: match = regex.match(string) result = f"Pattern: {pattern}; String: {string}; Matched: {bool(match)}" print(result)
該代碼的輸出如下:
Pattern: hello$; String: world hello; Matched: False Pattern: hello$; String: python38; Matched: False Pattern: \d$; String: world hello; Matched: False Pattern: \d$; String: python38; Matched: True
正如預期的那樣,第一個模式沒有匹配任何輸入字元串,然而第二個模式匹配了以數字結尾的字元串。
三、使用$n引用捕獲組的內容
假設我們想從一個字元串中提取日期。例如,我們有一個包含日期的字元串,格式為”dd-mm-yyyy”,我們想要分別提取每個日期組件,並將它們存儲在一個元組中。我們可以使用正則表達式和捕獲組來完成這個任務。
為了提取日期,我們可以先編寫一個匹配日期格式的正則表達式模式:r”(\d{2})-(\d{2})-(\d{4})”。該模式包含三個捕獲組,分別匹配日期的日、月和年。然後我們可以使用group函數提取每個捕獲組的內容,並將它們存儲在一個元組中。
import re date_regex = re.compile(r"(\d{2})-(\d{2})-(\d{4})") date_string = "07-03-2021" match = date_regex.match(date_string) if match: date_components = match.groups() print(date_components) else: print("No match.")
該代碼輸出如下結果:
('07', '03', '2021')
正如預期的那樣,元組中包括日期的三個組成部分。這三個組件分別是日、月、年。
四、結論
Python正則表達式的$符號是一種非常有用的工具,可以幫助我們更準確地定義需要匹配的字元串。在大多數情況下,$符號將用於正則表達式模式的末尾,以確保匹配字元串的結尾部分。此外,通過結合捕獲組和$符號,我們可以輕鬆地從字元串中提取有用的信息。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/197122.html