代码详解:Python正则表达式的终极使用指南

本文详细介绍了Python正则表达式的使用,包括如何创建模式、使用常用操作符、元序列以及正则表达式函数。通过实例解析,展示了如何查找标点符号、创建复杂模式以及在文本中查找电子邮件、域名等。正则表达式在处理文本数据时能极大提升效率。
摘要由CSDN通过智能技术生成

全文共8032字,预计学习时长16分钟

处理文本数据的一个主要任务就是创建许多以文本为基础的特性。

人们可能想要在文本中找出特定格式的内容,比如找出存在于文本中的电子邮件,或者大型文本中的电话号码。

虽然想要实现上述功能听起来很繁琐,但是如果使用Python正则表达式模块,就可以使这一操作更加简单。

假设要在一篇特定的文章中找出标点符号的数量。以狄更斯的作品文本为例。

你通常会怎么做?

最简单的方法如下:

target = [';','.',',','–']

string = "It was the best of times, it was the worst of times, it was
 the age of wisdom, it was the age of foolishness, it was the epoch of
 belief, it was the epoch of incredulity, it was the season of Light, it
 was the season of Darkness, it was the spring of hope, it was the 
winter of despair, we had everything before us, we had nothing before
 us, we were all going direct to Heaven, we were all going direct the 
other way – in short, the period was so far like the present period,
 that some of its noisiest authorities insisted on its being received,
 for good or for evil, in the superlative degree of comparison only."
num _ points = 0
num_puncts = 0
for punct in target:
    if punct in string:
        num_puncts+=string.count(punct)print(num_puncts)
------------------------------------------------------------------
19

如果没有可支配的re模块,那就要用到上面的代码。但如果有re模块,则只需两行代码:

import re
pattern = r"[;.,–]"
print(len(re.findall(pattern,string)))
------------------------------------------------------------------
19

本文讨论的是最常用的正则表达式模式,以及一些经常使用的正则表达式函数。

什么是正则表达式?

简而言之,正则表达式(regex)用于探索给定字符串中的固定模式。

我们想找到的模式可以是任何东西。

可以创建类似于查找电子邮件或手机号码的模式。还可以创建查找以a开头、以z结尾的字符串的模式。

在上面的例子中:

import re

pattern = r'[,;.,–]'
print(len(re.findall(pattern,string)))

我们想找出的模式是 r’[,;.,–]’。这个模式可找出想要的4个字符中的任何一个。regex101是一个用于测试模式的工具。将模式应用到目标字符串时,呈现出以下界面。

如图所示,可以在目标字符串中根据需要找到,;.,–。

每当需要测试正则表达式时,都会用到上面的工具。这比一次又一次运行python要快得多,调试也容易得多。

现在我们已经可以在目标字符串中找到这些模式,那么如何真正创建这些模式呢?

创建模式

使用正则表达式时,首先需要学习的是如何创建模式。

接下来将对一些最常用的模式进行逐一介绍。

可以想到最简单的模式是一个简单的字符串。

pattern = r'times'

string =
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值