如何使用 Python 中的 RegEx 模組匹配模式和字串


簡介

RegEx 模組代表正則表示式。如果您已經從事過程式設計工作,那麼您可能已經多次遇到過這個術語。我們使用正則表示式進行搜尋和替換,它被用於各種文字編輯器、搜尋引擎、文字處理器等。

換句話說,它有助於匹配您正在尋找的特定模式。

一個很好的例子是,您的學院網站如何允許您僅使用您的大學郵箱,而不能使用其他任何副檔名。

入門

正則表示式模組打包在 Python 中。您無需單獨下載和安裝它。

為了開始訪問其內容,我們必須首先匯入該模組。要匯入 RegEx 模組,我們使用

import re

探索不同的函式

RegEx 模組附帶了許多函式,瞭解和掌握每個函式之間的區別至關重要。

下面列出了一些您在開始 Python 專案時肯定最常使用的重要函式。

示例

re.compile(pattern, flags) #Compiles the pattern to be matched
re.search(pattern, string, flags) #Searches through the string for exact match
re.match(pattern, string, flags) #Checks if there is a match between pattern and string
re.split(pattern, string, max, flag) #Splits the string based on the pattern provided
re.findall(pattern, string, flag) #Prints all the matches found using the pattern
re.finditer(pattern, string, flags) #Returns the string as an iterable object
re.sub(pattern, repl, string, count) #Replaces the string with the pattern
re.subn(pattern, repl, string, count) #Does the same thing as re.sub but returns it in a tuple(string and count)
re.escape(pattern) #Escapes all characters other than ascii characters

re.compile 和 re.match 函式

讓我們取一個字串,例如“Hello world”。現在,讓我們找出上述字串是否出現在字串“Hello world! How are things going?”中。

為此,我們使用 re.compile 和 re.match 函式。

x = re.compile(“Hello world”)
y = x.match(“Hello world! How are things going?”)
if (y):
   print("Strings match")
else:
   print("Strings do not match")

輸出

Strings match

如果您想知道,為什麼我們不能在不使用 compile 函式的情況下做到這一點,您的想法是正確的!我們可以在不使用 compile 函式的情況下做到這一點。

x = re.match(“Hello world”,"Hello world! How are things going?")
if (y):
   print("Strings match")
else:
   print("Strings do not match")

輸出

String match

re.split 函式

x = re.split("\W+","Hello,World")
print(x)
x = re.split("(\W+)","Hello,World
print(x)

輸出

['Hello', 'World']
['Hello', ',', 'World']

在上面的示例中,“\W+”基本上表示從左側開始分割,並且 + 號表示繼續向前移動直到結束。當它像案例 2 中那樣用括號括起來時,它也會分割並新增標點符號,例如逗號。

re.sub 和 re.subn 函式

x = re.sub(r"there","World","Hello there. Python is fun.")
print(x)

x = re.subn(r"there","World","Hello there. Python is fun. Hello there")
print(x)

輸出

Hello World. Python is fun.
('Hello World. Python is fun. Hello World', 2)

在上面的示例中,re.sub 檢查單詞“there”是否存在並將其替換為“world”。

subn 函式執行完全相同的操作,但返回一個元組而不是字串,並且還添加了所執行的替換總數。

現實世界中的示例

使用 RegEx 模組的一個實際應用/示例是驗證密碼。

import re
matching_sequence = r"[0−9]"
while(True):
   x = input("Enter your password : ")
   r = re.search(matching_sequence,x)
   if (r and len(x)>6):
      print(x + " is a valid password")
   else:
      print(x + " is not a valid password. Password MUST be atleast 7 characters with atleast 1 number")
   input("Press Enter key to exit ")

程式將檢查您是否輸入了有效的密碼(7 個或更多字元,至少包含一個數字)或不是。

結論

您已經學習了 Python 中存在的 RegEx 模組的基本知識以及其中所有各種不同的函式。

RegEx 模組還有更多函式和用途。如果您有興趣,您可以從其官方文件中閱讀更多內容:https://docs.python.club.tw/3/library/re.html

更新於: 2021年2月11日

193 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.