Python教程-Python正则表达式中的re.search()与re.findall()

正则表达式,也称为有理表达式,是一系列用于定义搜索模式的字符序列。它主要用于与字符串或字符串匹配,例如查找和替换操作。正则表达式是一种通用的匹配字符序列模式的方式。
模块正则表达式(RE)用于指定与模式匹配的字符串集。为了理解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模块,并使用正则表达式匹配数据字符串与模式,即今天是周几和日期。
表达式"([A-Za-z]+) (d+)"应该与导入的数据字符串匹配。然后,它将打印[6, 16],因为它在索引25处匹配字符串并在索引35结束。我们使用group()函数来获取所有匹配和捕获组,以获取模式中所需的输出。这些组包含匹配的值,例如:
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正则表达式中re.search()方法和re.findall()方法之间的区别,并提供了示例。