re模块提供对Python中正则表达式的支持。以下是此模块中的主要方法。
搜索模式的出现
re.search():此方法返回None(如果模式不匹配),或者返回re.MatchObject,其中包含有关字符串的匹配部分的信息。此方法在第一个匹配项后停止,因此它最适合测试正则表达式,而不是提取数据。
import re
# 让我们使用正则表达式来匹配日期字符串
# 以月份名称的形式,后跟日号
regex = r"([a-zA-Z]+) (\d+)"
match = re.search(regex, "I was born on June 24")
if match != None:
# [当表达式"([a-za-Z])(d=)])])]到达此处时,我们到达这里。
# 与日期字符串匹配。
# 这将打印 +14, 21),因为它匹配在索引 14
#和结束于 21 。
print "Match at index %s, %s" % (match.start(), match.end())
# 我们组()方法,以获得所有的匹配和
# 捕获的组。这些组包含匹配的值。
# 特别是:
# match. group (0) 始终返回完全匹配的字符串
# _ match. 组 (1) 匹配. 组 (2),...返回捕获
# 按输入字符串中从左到右的顺序组
# match. group() 等效于 match. group(0)
# 这将打印"6月24日"
print "Full match: %s" % (match.group(0))
# 这将打印 "June"
print "Month: %s" % (match.group(1))
# 打印 "24"
print "Day: %s" % (match.group(2))
else:
print "The regex pattern does not match."
输出:
Match at index 14, 21
Full match: June 24
Month: June
Day: 24
匹配文本模式
re.match():此函数尝试将模式匹配到整个字符串。re.match函数成功返回匹配对象,失败则返回None。
re.match(pattern, string, flags=0)
pattern : Regular expression to be matched.
string : String where p attern is searched
flags : We can specify different flags
using bitwise OR (|).
import re
# 使用正则表达式的示例函数
# 查找日期的月份和日期。
def findMonthAndDate(string):
regex = r"([a-zA-Z]+) (\d+)"
match = re.match(regex, string)
if match == None:
print "Not a valid date"
return
print "Given Data: %s" % (match.group())
print "Month: %s" % (match.group(1))
print "Day: %s" % (match.group(2))
# 驱动程序代码
findMonthAndDate("Jun 24")
print("")
findMonthAndDate("I was born on June 24")
查找所有出现的模式
re.findall():以字符串列表形式返回字符串中所有不重复的模式匹配项。字符串从左到右扫描,并以找到的顺序返回匹配项
# Python 程序,用于演示
# 找到所有 ()
import re
# 一个示例文本字符串,其中正则表达式
# 被搜索。
string = """Hello my Number is 123456789 and
my friend's number is 987654321"""
# 用于查找数字的示例正则表达式。
regex = '\d+'
match = re.findall(regex, string)
print(match)
输出:
['123456789','987654321']
正则表达式是一个巨大的话题。这是一个完整的库。正则表达式可以做很多事情。您可以匹配,搜索,替换,提取大量数据。例如,下面的小代码是如此强大,以至于它可以从文本中提取电子邮件地址。因此,我们可以使用easy.Lake regex查看python中的Web爬网程序和爬虫。
# 提取所有电子邮件地址并将其添加到结果集
new_emails = set(re.findall(r"[a-z0-9\.\-+_]+@[a-z0-9\.\-+_]+\.[a-z]+",
text, re.I))