使用正则表达式在 Python 中进行模式匹配

pythonserver side programmingprogramming更新于 2025/5/13 0:44:17

什么是正则表达式?

在现实世界中,大多数编程语言中的字符串解析都由正则表达式处理。Python 编程语言中的正则表达式是一种用于匹配文本模式的方法。

每个 Python 安装附带的 “re” 模块提供正则表达式支持。

在 Python 中,正则表达式搜索通常写为:

match = re.search(pattern, string)

re.search() 方法接受两个参数,一个正则表达式模式和一个字符串,并在字符串中搜索该模式。如果在字符串中找到该模式,search() 将返回匹配对象,否则返回 None。因此,在正则表达式中,给定一个字符串,确定该字符串是否与给定的模式匹配,并且(可选)收集包含相关信息的子字符串。正则表达式可用于回答 − 之类的问题

  • 此字符串是否为有效 URL?

  • /etc/passwd 中的哪些用户属于给定组?

  • 日志文件中所有警告消息的日期和时间是什么?

  • 访问者输入的 URL 请求了哪些用户名和文档?

匹配模式

正则表达式是复杂的微型语言。它们依靠特殊字符来匹配未知字符串,但让我们从文字字符(例如字母、数字和空格字符)开始,这些字符始终与自身匹配。让我们看一个基本示例:

#需要模块 're'用于正则表达式
import re
#
search_string = "TutorialsPoint"
pattern = "Tutorials"
match = re.match(pattern, search_string)
#search() 后的 If 语句测试是否成功
if match:
   print("regex matches: ", match.group())
else:
   print('pattern not found')

结果

regex matches: Tutorials

匹配字符串

python 的 “re” 模块有许多方法,要测试特定正则表达式是否与特定字符串匹配,可以使用 re.search()。 re.MatchObject 提供其他信息,例如匹配项位于字符串的哪一部分。

语法

matchObject = re.search(pattern, input_string, flags=0)

示例

#需要模块 're' 用于正则表达式
import re
#让我们使用正则表达式来匹配日期字符串。
regex = r"([a-zA-Z]+) (\d+)"
if re.search(regex, "Jan 2"):
   match = re.search(regex, "Jan 2")
   #这将打印 [0, 5),因为它匹配了
   # 字符串
   print("Match at index %s, %s" % (match.start(), match.end()))
   # 组包含匹配的值。具体来说:
   # match.group(0) 始终返回完全匹配的字符串
   # match.group(1), match.group(2), ... 将返回捕获
   # 在输入字符串中按从左到右的顺序分组  
   # match.group() 等同于 match.group(0)
   # 因此这将打印 "Jan 2"
   print("Full match: %s" % (match.group(0)))
   # 因此这将打印 "Jan"
   print("Month: %s" % (match.group(1)))
   # 因此这将打印 "2"
   print("Day: %s" % (match.group(2)))
else:
   # 如果 re.search() 不匹配,则返回 None
   print("Pattern not Found! ")

结果

Match at index 0, 5
Full match: Jan 2
Month: Jan
Day: 2

由于上述方法在第一次匹配后停止,因此更适合测试正则表达式而不是提取数据。

捕获组

如果模式包含两个或多个括号,则最终结果将是一个元组而不是字符串列表,借助括号()组机制和finall()。每个匹配的模式都由一个元组表示,每个元组包含组(1)、组(2)……数据。

import re
regex = r'([\w\.-]+)@([\w\.-]+)'
str = ('hello john@hotmail.com, hello@Tutorialspoint.com, hello python@gmail.com')
matches = re.findall(regex, str)
print(matches)
for tuple in matches:
   print("Username: ",tuple[0]) #username
   print("Host: ",tuple[1]) #host

结果

[('john', 'hotmail.com'), ('hello', 'Tutorialspoint.com'), ('python', 'gmail.com')]
Username: john
Host: hotmail.com
Username: hello
Host: Tutorialspoint.com
Username: python
Host: gmail.com

查找和替换字符串

另一个常见任务是在给定字符串中搜索模式的所有实例并替换它们,re.sub(pattern, replacement, string) 就可以做到这一点。例如,替换旧电子邮件域的所有实例

代码

# requid 库
import re
#给定字符串
str = ('hello john@hotmail.com, hello@Tutorialspoint.com, hello python@gmail.com, Hello World!')
#要匹配的模式
pattern = r'([\w\.-]+)@([\w\.-]+)'
#用字符串替换匹配的模式,
replace = r'\1@XYZ.com'
   ## re.sub(pat, replacement, str) -- 返回包含所有替换项的新字符串,
   ## \1 是 group(1),\2 是替换项中的 group(2)
print (re.sub(pattern, replace, str))

结果

hello john@XYZ.com, hello@XYZ.com, hello python@XYZ.com, Hello World!

Re 选项标志

在如上的 Python 正则表达式中,我们可以使用不同的选项来修改模式匹配的行为。这些额外的参数,可选的标志被添加到search()或findall()等函数中,例如re.search(pattern, string, re.IGNORECASE)。

  • IGNORECASE −

    顾名思义,它使模式不区分大小写(大写/小写),这样,包含‘a’和‘A’的字符串都匹配。

  • DOTALL

    re.DOTALL允许点(.)元字符匹配所有字符,包括换行符(\n)。

  • MULTILINE

    re.MULTILINE允许匹配字符串每一行的开始(^)和结束($)。但是,通常,^和&只会匹配整个字符串的开头和结尾。


相关文章


有用资源