Python 正则表达式模式匹配
什么是正则表达式?
在现实世界中,大多数编程语言中的字符串解析都是由正则表达式处理的。在 Python 编程语言中,正则表达式是一种用于匹配文本模式的方法。
每个 Python 安装都自带的“re”模块提供正则表达式支持。
在 Python 中,正则表达式搜索通常写成如下形式:
match = re.search(pattern, string)
re.search() 方法接受两个参数:正则表达式模式和一个字符串,并在字符串中搜索该模式。如果在字符串中找到该模式,search() 返回一个匹配对象;否则返回 None。因此,在正则表达式中,给定一个字符串,确定该字符串是否与给定模式匹配,并可选地收集包含相关信息的子字符串。正则表达式可以用来回答以下问题:
这个字符串是有效的 URL 吗?
/etc/passwd 中哪些用户属于给定的组?
日志文件中所有警告消息的日期和时间是什么?
访问者键入的 URL 请求了哪个用户名和文档?
匹配模式
正则表达式是一种复杂的迷你语言。它们依赖于特殊字符来匹配未知字符串,但让我们从字面字符开始,例如字母、数字和空格字符,它们始终匹配自身。让我们来看一个基本的例子
#Need module 're' for regular expression
import re
#
search_string = "TutorialsPoint"
pattern = "Tutorials"
match = re.match(pattern, search_string)
#If-statement after search() tests if it succeeded
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)
示例
#Need module 're' for regular expression
import re
# Lets use a regular expression to match a date string.
regex = r"([a-zA-Z]+) (\d+)"
if re.search(regex, "Jan 2"):
match = re.search(regex, "Jan 2")
# This will print [0, 5), since it matches at the beginning and end of the
# string
print("Match at index %s, %s" % (match.start(), match.end()))
# The groups contain the matched values. In particular:
# match.group(0) always returns the fully matched string
# match.group(1), match.group(2), ... will return the capture
# groups in order from left to right in the input string
# match.group() is equivalent to match.group(0)
# So this will print "Jan 2"
print("Full match: %s" % (match.group(0)))
# So this will print "Jan"
print("Month: %s" % (match.group(1)))
# So this will print "2"
print("Day: %s" % (match.group(2)))
else:
# If re.search() does not match, then None is returned
print("Pattern not Found! ")结果
Match at index 0, 5 Full match: Jan 2 Month: Jan Day: 2
由于上述方法在第一次匹配后停止,因此它更适合于测试正则表达式而不是提取数据。
捕获组
如果模式包含两个或多个括号,则最终结果将是一个元组而不是字符串列表,借助括号 () 组机制和 findall()。每个匹配的模式都由一个元组表示,每个元组包含 group(1)、group(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 library
import re
#given string
str = ('hello john@hotmail.com, hello@Tutorialspoint.com, hello python@gmail.com, Hello World!')
#pattern to match
pattern = r'([\w\.-]+)@([\w\.-]+)'
#replace the matched pattern from string with,
replace = r'\1@XYZ.com'
## re.sub(pat, replacement, str) -- returns new string with all replacements,
## \1 is group(1), \2 group(2) in the replacement
print (re.sub(pattern, replace, str))结果
hello john@XYZ.com, hello@XYZ.com, hello python@XYZ.com, Hello World!
正则表达式选项标志
在上面的 Python 正则表达式中,我们可以使用不同的选项来修改模式匹配的行为。这些额外的参数,可选标志添加到 search() 或 findall() 等函数中,例如 re.search(pattern, string, re.IGNORECASE)。
IGNORECASE:
顾名思义,它使模式不区分大小写(大写/小写),这样包含“a”和“A”的字符串都匹配。
DOTALL
re.DOTALL 允许点 (.) 元字符匹配所有字符,包括换行符 (\n)。
MULTILINE
re.MULTILINE 允许匹配字符串每一行的开头 (^) 和结尾 ($) 。但是,通常情况下,^ 和 $ 只会匹配整个字符串的开头和结尾。
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP