如何在Python中使用RegEx模块匹配模式和字符串

介绍

RegEx模块代表正则表达式。如果您已经从事编程工作,那么您可能已经多次遇到过这个术语。我们使用正则表达式进行搜索和替换,它在各种文本编辑器,搜索引擎,文字处理器等中使用。

换句话说,它有助于匹配您要寻找的特定模式。

一个很好的例子就是拼贴网站如何只允许您使用大学邮件,而不能使用其他任何扩展名。

入门

正则表达式模块打包在Python中。您无需单独下载和安装。

为了开始访问其内容,我们必须首先导入模块。要导入RegEx模块,我们使用

import re

探索不同的功能

RegEx模块具有许多功能,必须了解并了解它们之间的区别是至关重要的。

下面提到的是您在开始处理Python项目时最肯定会使用的一些重要功能。

示例

re.compile(pattern, flags) #编译要匹配的模式
re.search(pattern, string, flags) #在字符串中搜索完全匹配
re.match(pattern, string, flags) #检查模式和字符串之间是否匹配
re.split(pattern, string, max, flag) #根据提供的模式分割字符串
re.findall(pattern, string, flag) #打印使用模式找到的所有匹配项
re.finditer(pattern, string, flags) #将字符串作为可迭代对象返回
re.sub(pattern, repl, string, count) #用模式替换字符串
re.subn(pattern, repl, string, count) #做相同的事情asre.sub,但返回一个元组(字符串和计数)
re.escape(pattern) #Escapes all characters other than ascii characters

重新编译和re.match功能

让我们说一个字符串,说“ Hello world”。现在,让我们找出字符串“ Hello world!”中是否存在上述字符串。事情进行得如何?”

为此,我们使用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函数就无法执行此操作,那么您是对的!我们可以不用编译功能就可以做到这一点。

x = re.match(“Hello world”,"Hello world! How are things going?")
if (y):
   print("Strings match")
else:
   print("Strings do not match")
输出结果
String match

重新分割功能

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.python.org/3/library/re.html上阅读其官方文档中的更多内容。

猜你喜欢