正则表达式也称为有理表达式,是用于定义搜索模式的字符序列。它主要用于字符串的模式匹配或字符串匹配,如查找和替换操作。正则表达式是将模式与字符序列进行匹配的通用方式。
模块正则表达式用于指定与模式匹配的字符串集。为了理解 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() 方法之间的区别,并给出了示例。