使用Regex在Python中进行模式匹配

什么是正则表达式?

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

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

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

match = re.search(pattern, string)

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

  • 该字符串是有效的网址吗?

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

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

  • 访问者键入的URL要求提供什么用户名和文档?

匹配模式

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

#需要模块“ re”进行正则表达式
import re
#
search_string = "nhooo"
pattern = "Tutorials"
match = re.match(pattern, search_string)
#If-statement after search() tests if it succeeded
if match:
   print("正则表达式匹配: ", match.group())
else:
   print('pattern not found')

结果

正则表达式匹配: Tutorials

匹配字符串

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

语法

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

示例

#需要模块“ re”进行正则表达式
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")


   print("Match at index %s, %s" % (match.start(), match.end()))

   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("找不到! ")

结果

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

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

捕获组

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

import re
regex = r'([\w\.-]+)@([\w\.-]+)'
str = ('hello john@hotmail.com, hello@Nhooo.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', 'Nhooo.com'), ('python', 'gmail.com')]
Username: john
Host: hotmail.com
Username: hello
Host: Nhooo.com
Username: python
Host: gmail.com

查找和替换字符串

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

# requid library
import re
#given string
str = ('hello john@hotmail.com, hello@Nhooo.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”的字符串都匹配。

  • 点点

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

  • 多线

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