如何使用 Python 中的 RegEx 模块匹配模式和字符串
简介
RegEx 模块代表正则表达式。如果您已经从事过编程工作,那么您可能已经多次遇到过这个术语。我们使用正则表达式进行搜索和替换,它被用于各种文本编辑器、搜索引擎、文字处理器等。
换句话说,它有助于匹配您正在寻找的特定模式。
一个很好的例子是,您的学院网站如何允许您仅使用您的大学邮箱,而不能使用其他任何扩展名。
入门
正则表达式模块打包在 Python 中。您无需单独下载和安装它。
为了开始访问其内容,我们必须首先导入该模块。要导入 RegEx 模块,我们使用
import re
探索不同的函数
RegEx 模块附带了许多函数,了解和掌握每个函数之间的区别至关重要。
下面列出了一些您在开始 Python 项目时肯定最常使用的重要函数。
示例
re.compile(pattern, flags) #Compiles the pattern to be matched re.search(pattern, string, flags) #Searches through the string for exact match re.match(pattern, string, flags) #Checks if there is a match between pattern and string re.split(pattern, string, max, flag) #Splits the string based on the pattern provided re.findall(pattern, string, flag) #Prints all the matches found using the pattern re.finditer(pattern, string, flags) #Returns the string as an iterable object re.sub(pattern, repl, string, count) #Replaces the string with the pattern re.subn(pattern, repl, string, count) #Does the same thing as re.sub but returns it in a tuple(string and count) re.escape(pattern) #Escapes all characters other than ascii characters
re.compile 和 re.match 函数
让我们取一个字符串,例如“Hello world”。现在,让我们找出上述字符串是否出现在字符串“Hello world! How are things going?”中。
为此,我们使用 re.compile 和 re.match 函数。
x = re.compile(“Hello world”)
y = x.match(“Hello world! How are things going?”)
if (y):
print("Strings match")
else:
print("Strings do not match")输出
Strings match
如果您想知道,为什么我们不能在不使用 compile 函数的情况下做到这一点,您的想法是正确的!我们可以在不使用 compile 函数的情况下做到这一点。
x = re.match(“Hello world”,"Hello world! How are things going?")
if (y):
print("Strings match")
else:
print("Strings do not match")输出
String match
re.split 函数
x = re.split("\W+","Hello,World")
print(x)
x = re.split("(\W+)","Hello,World
print(x)输出
['Hello', 'World'] ['Hello', ',', 'World']
在上面的示例中,“\W+”基本上表示从左侧开始分割,并且 + 号表示继续向前移动直到结束。当它像案例 2 中那样用括号括起来时,它也会分割并添加标点符号,例如逗号。
re.sub 和 re.subn 函数
x = re.sub(r"there","World","Hello there. Python is fun.") print(x) x = re.subn(r"there","World","Hello there. Python is fun. Hello there") print(x)
输出
Hello World. Python is fun.
('Hello World. Python is fun. Hello World', 2)在上面的示例中,re.sub 检查单词“there”是否存在并将其替换为“world”。
subn 函数执行完全相同的操作,但返回一个元组而不是字符串,并且还添加了所执行的替换总数。
现实世界中的示例
使用 RegEx 模块的一个实际应用/示例是验证密码。
import re
matching_sequence = r"[0−9]"
while(True):
x = input("Enter your password : ")
r = re.search(matching_sequence,x)
if (r and len(x)>6):
print(x + " is a valid password")
else:
print(x + " is not a valid password. Password MUST be atleast 7 characters with atleast 1 number")
input("Press Enter key to exit ")程序将检查您是否输入了有效的密码(7 个或更多字符,至少包含一个数字)或不是。
结论
您已经学习了 Python 中存在的 RegEx 模块的基本知识以及其中所有各种不同的函数。
RegEx 模块还有更多函数和用途。如果您有兴趣,您可以从其官方文档中阅读更多内容:https://docs.pythonlang.cn/3/library/re.html。
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP