正則表達式也稱為有理表達式,是用於定義搜索模式的字符序列。它主要用於字符串的模式匹配或字符串匹配,如查找和替換操作。正則表達式是將模式與字符序列進行匹配的通用方式。
模塊正則表達式用於指定與模式匹配的字符串集。為了理解 RE 類比,元字符用於 RE 模塊的功能中。
共有 14 個元字符,,我們將在它們進入函數時討論它們:
\ : It is used for dropping the special meaning of character following it
[] : It is used for representing a character class
^ : It is used for matching the beginning
$ : It is used for matching the end
. : It is used for matching any character except newline
? : It is used for matching zero or one occurrence.
| : It means OR. This is used for matching with any of the characters separated by it.
* : It is used for any number of occurrences (including 0 occurrences)
+ : It is used for one or more occurrences
{} : It is used for indicating the number of occurrences of the preceding RE to match.
() : It is used for enclosing the group of REs.
re.search()方法
re.search() 方法用於返回 None(如果模式不匹配)或 re。MatchObject 包含字符串匹配部分的所有信息。此方法在第一次匹配後停止運行,因此這比提取數據更適合測試正則表達式。
示例:
import re
# We will use the regular expression for matching the string of data
# in the form of Weekday's name followed by day number
regex = r"([A-Za-z]+) (\d+)"
match = re.search(regex, "Day and Date of Today is Tuesday 12")
if match != None:
print ("The String match at index % s, % s" % (match.start(), match.end()))
print ("Full match of Pattern: % s" % (match.group(0)))
print ("The Weekday of Today is: % s" % (match.group(1)))
print ("The Date of Today is: % s" % (match.group(2)))
else:
print ("The pattern of Python regex does not match with the string of Data imported.")
輸出:
The String match at index 25, 35
Full match of Pattern: Tuesday 12
The Weekday of Today is: Tuesday
The Date of Today is: 12
說明:
在上面的代碼中,我們導入了 re 模塊,並使用正則表達式將數據字符串與模式匹配,即 Weekday 和 Date of Today。
表達式([A-Za-z]+)(\ d+)”應與導入的數據字符串匹配。然後,它將打印【25,35th】,因為它匹配第 25 個索引處的字符串,並作為第 35 個索引號結束。我們已經使用了組()功能來獲取所有匹配,並捕獲組來獲取模式中所需的輸出。這些組包含匹配的值。例如:
match.group(0) 將始終返回完全匹配的數據字符串,
match.group(1) 和 match.group(2) 將按照輸入字符串中從左到右的順序返回捕獲組。 (match.group() 也表示 match.group(0))。如果數據字符串與模式匹配,將按正確的順序打印;否則,它將使用 else 語句。
re.findall()方法
re.findall() 方法用於以字符串列表的形式獲取數據字符串中模式的所有非重疊匹配作為返回。數據字符串將從左到右掃描,其匹配項將以與找到的順序相同的順序返回。
示例:
import re
# The string of text where regular expression will be searched.
string_1 = """Here are some student's ID, student A: 676
student B: 564
student C: 567
student D: 112
student E: 234"""
# Setting the regular expression for finding digits in the string.
regex_1 = "(\d+)"
match_1 = re.findall(regex_1, string_1)
print(match_1)
輸出:
['676', '564', '567', '112', '234']
說明:
在上面的代碼中,我們首先導入包含一些數字的文本字符串。然後我們設置正則表達式 “(\d+)” 來匹配字符串和模式。匹配將是文本字符串中不重疊的數據。導入 re.findall() 方法後,我們得到字符串的非重疊匹配數據作為輸出。
結論
在本教程中,我們討論了 Python regex 中的 re.search() 方法和 re.findall() 方法之間的區別,並給出了示例。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/241568.html