Python 正則表示式模式匹配


什麼是正則表示式?

在現實世界中,大多數程式語言中的字串解析都是由正則表示式處理的。在 Python 程式語言中,正則表示式是一種用於匹配文字模式的方法。

每個 Python 安裝都自帶的“re”模組提供正則表示式支援。

在 Python 中,正則表示式搜尋通常寫成如下形式:

match = re.search(pattern, string)

re.search() 方法接受兩個引數:正則表示式模式和一個字串,並在字串中搜索該模式。如果在字串中找到該模式,search() 返回一個匹配物件;否則返回 None。因此,在正則表示式中,給定一個字串,確定該字串是否與給定模式匹配,並可選地收集包含相關資訊的子字串。正則表示式可以用來回答以下問題:

  • 這個字串是有效的 URL 嗎?

  • /etc/passwd 中哪些使用者屬於給定的組?

  • 日誌檔案中所有警告訊息的日期和時間是什麼?

  • 訪問者鍵入的 URL 請求了哪個使用者名稱和文件?

匹配模式

正則表示式是一種複雜的迷你語言。它們依賴於特殊字元來匹配未知字串,但讓我們從字面字元開始,例如字母、數字和空格字元,它們始終匹配自身。讓我們來看一個基本的例子

線上演示

#Need module 're' for regular expression
import re
#
search_string = "TutorialsPoint"
pattern = "Tutorials"
match = re.match(pattern, search_string)
#If-statement after search() tests if it succeeded
if match:
   print("regex matches: ", match.group())
else:
   print('pattern not found')

結果

regex matches: Tutorials

匹配字串

Python 的“re”模組有很多方法,要測試特定的正則表示式是否與特定字串匹配,可以使用 re.search()。re.MatchObject 提供其他資訊,例如在字串的哪個部分找到匹配項。

語法

matchObject = re.search(pattern, input_string, flags=0)

示例

線上演示

#Need module 're' for regular expression
import re
# Lets use a regular expression to match a date string.
regex = r"([a-zA-Z]+) (\d+)"
if re.search(regex, "Jan 2"):
   match = re.search(regex, "Jan 2")
   # This will print [0, 5), since it matches at the beginning and end of the
   # string
   print("Match at index %s, %s" % (match.start(), match.end()))
   # The groups contain the matched values. In particular:
   # match.group(0) always returns the fully matched string
   # match.group(1), match.group(2), ... will return the capture
   # groups in order from left to right in the input string  
   # match.group() is equivalent to match.group(0)
   # So this will print "Jan 2"
   print("Full match: %s" % (match.group(0)))
   # So this will print "Jan"
   print("Month: %s" % (match.group(1)))
   # So this will print "2"
   print("Day: %s" % (match.group(2)))
else:
   # If re.search() does not match, then None is returned
   print("Pattern not Found! ")

結果

Match at index 0, 5
Full match: Jan 2
Month: Jan
Day: 2

由於上述方法在第一次匹配後停止,因此它更適合於測試正則表示式而不是提取資料。

捕獲組

如果模式包含兩個或多個括號,則最終結果將是一個元組而不是字串列表,藉助括號 () 組機制和 findall()。每個匹配的模式都由一個元組表示,每個元組包含 group(1)、group(2)……資料。

線上演示

import re
regex = r'([\w\.-]+)@([\w\.-]+)'
str = ('hello john@hotmail.com, hello@Tutorialspoint.com, hello python@gmail.com')
matches = re.findall(regex, str)
print(matches)
for tuple in matches:
   print("Username: ",tuple[0]) #username
   print("Host: ",tuple[1]) #host

結果

[('john', 'hotmail.com'), ('hello', 'Tutorialspoint.com'), ('python', 'gmail.com')]
Username: john
Host: hotmail.com
Username: hello
Host: Tutorialspoint.com
Username: python
Host: gmail.com

查詢和替換字串

另一個常見任務是在給定字串中搜索模式的所有例項並替換它們,re.sub(pattern, replacement, string) 將準確執行此操作。例如,要替換舊電子郵件域的所有例項

程式碼

線上演示

# requid library
import re
#given string
str = ('hello john@hotmail.com, hello@Tutorialspoint.com, hello python@gmail.com, Hello World!')
#pattern to match
pattern = r'([\w\.-]+)@([\w\.-]+)'
#replace the matched pattern from string with,
replace = r'\1@XYZ.com'
   ## re.sub(pat, replacement, str) -- returns new string with all replacements,
   ## \1 is group(1), \2 group(2) in the replacement
print (re.sub(pattern, replace, str))

結果

hello john@XYZ.com, hello@XYZ.com, hello python@XYZ.com, Hello World!

正則表示式選項標誌

在上面的 Python 正則表示式中,我們可以使用不同的選項來修改模式匹配的行為。這些額外的引數,可選標誌新增到 search() 或 findall() 等函式中,例如 re.search(pattern, string, re.IGNORECASE)。

  • IGNORECASE:

    顧名思義,它使模式不區分大小寫(大寫/小寫),這樣包含“a”和“A”的字串都匹配。

  • DOTALL

    re.DOTALL 允許點 (.) 元字元匹配所有字元,包括換行符 (\n)。

  • MULTILINE

    re.MULTILINE 允許匹配字串每一行的開頭 (^) 和結尾 ($) 。但是,通常情況下,^ 和 $ 只會匹配整個字串的開頭和結尾。

更新於:2020年6月30日

7K+ 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.