你能用簡單的方式解釋 Python 正則表示式語法嗎?
在本篇部落格中,您將學習正則表示式 (RegEx),並使用 Python 的 re 模組(藉助示例)與 RegEx 進行互動。
正則表示式 (RegEx) 是一系列字元,用於定義搜尋模式。例如,
^a...s$
上面的程式碼定義了一個 RegEx 模式。任何以 a 開頭,以 s 結尾的五字母字串都符合該模式。
Python 有一個名為 re 的模組用於處理 RegEx。以下是一個示例 -
import re
pattern = '^a...s$'
test_string = 'abyss'
result = re.match(pattern, test_string)
if result:
print("Search successful.")
else:
print("Search unsuccessful.")
用於這些操作的不同型別的語法
re.findall()
re.findall() 方法返回一個包含所有匹配項的字串列表。
示例
從字串中提取數字的程式
import re
string = 'hello 12 hi 89. Howdy 34'
pattern = '\d+'
print("Entered String=",string)
result = re.findall(pattern, string)
print("The numbers in the above string",result)
輸出
Entered String= hello 12 hi 89. Howdy 34 The numbers in the above string ['12', '89', '34']
如果未找到模式,re.findall() 將返回一個空列表。
re.search()
re.search() 方法接受兩個引數:一個模式和一個字串。該方法查詢 RegEx 模式與字串匹配的第一個位置。
如果搜尋成功,re.search() 將返回一個匹配物件;否則,它將返回 None。
字串
match = re.search(pattern, str)
示例
import re
string = "Python is fun"
#check if 'Python' is at the beginning
match = re.search('\APython', string)
if match:
print("pattern found inside the string")
else:
print("pattern not found")
輸出
pattern found inside the string
這裡,match 包含一個匹配物件。
re.subn()
re.subn() 與 re.sub() 類似,除了它返回一個包含新字串和替換次數的 2 個專案的元組。
示例
#Program to remove all whitespaces
import re
#multiline string
string = 'abc 12\
de 23 \n f45 6'
print("Orginal String =",string)
#matches all whitespace characters
pattern = '\s+'
#empty string
replace = ''
new_string = re.subn(pattern, replace, string)
print("New String=",new_string)
輸出
Orginal String = abc 12de 23
f45 6
New String= ('abc12de23f456', 4)
re.split()
re.split 在存在匹配項的地方拆分字串後,提供一個已拆分字串的列表。
示例
import re string = 'Twelve:12 Eighty nine:89.' pattern = '\d+' result = re.split(pattern, string) print(result)
輸出
['Twelve:', ' Eighty nine:', '.']
如果未找到模式,re.split() 將返回一個包含原始字串的列表。
您可以將 maxsplit 引數傳遞給 re.split() 方法。它是將發生的拆分最大次數。
示例
import re string = 'Twelve:12 Eighty nine:89 Nine:9.' pattern = '\d+' //maxsplit = 1 //split only at the first occurrence result = re.split(pattern, string, 1) print(result)
輸出
['Twelve:', ' Eighty nine:89 Nine:9.']
順便說一句,maxsplit 的預設值為 0;表示所有可能的拆分。
re.sub()
re.sub() 的語法為 -
re.sub(pattern, replace, string)
該方法返回一個字串,其中匹配的出現次數被 replace 變數的內容替換。
示例
#Program to remove all whitespaces import re #multiline string string = 'abc 12\ de 23 \n f45 6' #matches all whitespace characters pattern = '\s+' #empty string replace = '' new_string = re.sub(pattern, replace, string) print(new_string)
輸出
abc12\de23f456
如果未找到模式,re.sub() 將返回原始字串。
您可以將 count 作為第四個引數傳遞給 re.sub() 方法。如果省略,則結果為 0。這將替換所有出現。
示例
import re #multiline string string = "abc 12\ de 23 \n f45 6" #matches all whitespace characters pattern = '\s+' replace = '' new_string = re.sub(r'\s+', replace, string, 1) print(new_string)
輸出
abc12de 23 f45 6
匹配物件
您可以使用 dir() 函式獲取匹配物件的函式和屬性。
匹配物件的一些常用方法和屬性如下 -
match.group()
group() 方法返回字串中匹配的部分。
示例
import re
string = '39801 356, 2102 1111'
#Three digit number followed by space followed by two digit number
pattern = '(\d{3}) (\d{2})'
#match variable contains a Match object.
match = re.search(pattern, string)
if match:
print(match.group())
else:
print("pattern not found")
輸出
801 35
這裡,match 變數包含一個匹配物件。
我們的模式 (\d{3}) (\d{2}) 有兩個子組 (\d{3}) 和 (\d{2})。您可以獲取這些帶括號的子組的字串部分。方法如下 -
>>> match.group(1)
'801'
>>> match.group(2)
'35'
>>> match.group(1, 2)
('801', '35')
>>> match.groups()
('801', '35')
match.start(), match.end() and match.span()
The start() function returns the index of the start of the matched substring. Similarly, end() returns the end index of the matched substring.
>>> match.start()
2
>>> match.end()
8
The span() function returns a tuple containing start and end index of the matched part.
>>> match.span()
(2, 8)
match.re and match.string
The re attribute of a matched object returns a regular expression object. Similarly, string attribute returns the passed string.
>>> match.re
re.compile('(\d{3}) (\d{2})')
>>> match.string
'39801 356, 2102 1111'
我們已經涵蓋了 re 模組中所有常用的方法。如果您想了解更多資訊,請訪問 Python 3 re 模組。
在 RegEx 之前使用 r 字首
當在正則表示式之前使用 r 或 R 字首時,表示原始字串。例如,'\n' 是一個換行符,而 r'\n' 表示兩個字元:一個反斜槓 \ 後跟 n。
反斜槓 \ 用於轉義各種字元,包括所有元字元。但是,使用 r 字首會使 \ 作為普通字元對待。
示例
import re string = '\n and \r are escape sequences.' result = re.findall(r'[\n\r]', string) print(result)
輸出
['\n', '\r']
結論
因此,這些是我們試圖使用一些引人入勝的示例來解釋的最基本和最重要的正則表示式概念。其中一些是編造的,但大多數是我們清理資料時遇到的實際問題,因此,將來如果您遇到問題,請再次檢視示例;您可能會在那裡找到解決方案。
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP