9、Python标准库3正则表达式

目录

正则表达式的语法

参考链接
https://www.cnblogs.com/ldq2016/p/5528177.html
https://blog.csdn.net/qq_21188127/article/details/79269973
https://www.cnblogs.com/PythonHome/archive/2011/11/19/2255459.html


re模块

re所提供的两种操纵正则表达式的方法

直接使用正则表达式模块的函数

#!/usr/bin/env python
# encoding: utf-8

import re

text = 'alpha.2be2ta...gamma 2de2lta'

#用.和空格划分
print(re.split('[\. ]+', text))

#设置最大的匹配次数,分割了2次后,剩下的字符就不管了
print(re.split('[\. ]+', text, maxsplit=2))

pat = '[a-zA-z]+'
print(re.findall(pat, text))#查找单词,忽略掉中间的数字

#字符串替换
pat = '{name}'
text = 'Dear {name}...'
print(re.sub(pat, 'Mr.Dong', text))
#替换所出现的字符
str = 'a s d'
print(re.sub('a|s|d', 'good', str))

#字符串转义
print(re.escape('http://www.baidu.com'))

#匹配成功,返回match对象
print(re.match('done|quit', 'done!'))
#不成功,返回None
print(re.match('done|quit', 'doe!'))

#去除多余的空格
s = 'aaa    bb   c d e   fff'
print(' '.join(s.split()))#不使用正则
print(' '.join(re.split('[\s]+', s)))#联合使用
print(re.sub('\s+', ' ', s.strip()))#使用正则中的替换方法,strip删除两端空格

贪婪匹配和非贪婪匹配

贪婪匹配,尽量多地区匹配符合条件的内容
非贪婪匹配,匹配到一次即可

#!/usr/bin/env python
# encoding: utf-8

import re

#贪婪匹配
str = '<html><a>zeng1</a><a>zeng2</a></html>'
print(re.search('<.+>', str))#<_sre.SRE_Match object; span=(0, 37), match='<html><a>zeng1</a><a>zeng2</a></html>'>
#非贪婪匹配
print(re.search('<.+?>', str))#<_sre.SRE_Match object; span=(0, 6), match='<html>'>

使用正则表达式对象方法

当需要重复利用表达式或者想提高速度,那么可以使用正则表达式对象,此对象是使用re模块的compile()方法得到的,有了对象后,就可以使用对象提供的方法进行字符串处理了

对象的方法主要有
这里写图片描述
这里写图片描述

#!/usr/bin/env python
# encoding: utf-8

import re

text1 = 'alpha.2be2ta...gamma 2de2lta'
text2 = 'my name is zengraoli , and age is 24'
pattern = re.compile('[a-zA-z]+')
print(pattern.findall(text1))#['alpha', 'be', 'ta', 'gamma', 'de', 'lta']
print(pattern.findall(text2))#['my', 'name', 'is', 'zengraoli', 'and', 'age', 'is']

match对象

正则表达式或正则表达式对象的match()和search()匹配成功后都会返回match对象,其含有的对象属性与方法如下

这里写图片描述
下面例子使用group()

#!/usr/bin/env python
# encoding: utf-8

import re

m = re.match(r'(\w+) (\w+)', 'Isaac Newton, physicist')
print(m.group())#相当于m.group(0)
print(m.group(1))#返回第一个子模式内容
print(m.group(2))#返回第二个子模式内容
print(m.group(1, 2))#指定多个子模式

m = re.match(r'((?P<first>)\w+) (?P<second>\w+)', 'Isaac Newton, physicist')
print(m.groupdict())#以字典形式返回匹配结果

re中的三个常用模块re.compile、re.match、re.search的总结

re.matchre.search:search()会扫描整个string查找匹配;match()函数只检测是否在string的开始位置匹配

#!/usr/bin/env python
# encoding: utf-8

import re

print(re.match(r'raoli', 'zengraoli'))#None
print(re.search(r'raoli', 'zengraoli'))#<_sre.SRE_Match object; span=(4, 9), match='raoli'>

简单只使用一次两次,用re.matchre.search即可;多次重复使用则优先考虑re.compile

参考链接
https://www.cnblogs.com/papapython/p/7482349.html


正则表达式和字符串匹配

一个简单的小例子,实现以下功能

输入:完整网址
输出:域名部分
比如说,输入:
http://www.baidu.com/s?wd=%E7%88%AC%E8%99%AB&rsv_spt=1&rsv_iqid=0xea65e60300007d2a&issp=1&f=8&rsv_bp=0&rsv_idx=2&ie=utf-8&tn=02049043_62_pg&rsv_enter=1&rsv_sug3=5&rsv_sug1=3&rsv_sug7=100&rsv_sug2=0&inputT=1169&rsv_sug4=2873&rsv_sug=1
输出:www.baidu.com

两种方式来实现

字符串的匹配

content = "http://www.baidu.com/s?wd=%E7%88%AC%E8%99%AB&rsv_spt=1&rsv_iqid=0xea65e60300007d2a&issp=1&f=8&rsv_bp=0&rsv_idx=2&ie=utf-8&tn=02049043_62_pg&rsv_enter=1&rsv_sug3=5&rsv_sug1=3&rsv_sug7=100&rsv_sug2=0&inputT=1169&rsv_sug4=2873&rsv_sug=1"
len = len("http://")
pos = content.find('/', len)
print(content[len:pos])

正则表达式

#!/usr/bin/env python
# encoding: utf-8

import re

content = "https://www.baidu.com/s?wd=%E7%88%AC%E8%99%AB&rsv_spt=1&rsv_iqid=0xea65e60300007d2a&issp=1&f=8&rsv_bp=0&rsv_idx=2&ie=utf-8&tn=02049043_62_pg&rsv_enter=1&rsv_sug3=5&rsv_sug1=3&rsv_sug7=100&rsv_sug2=0&inputT=1169&rsv_sug4=2873&rsv_sug=1"
print(re.search(r'[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:~\+#])', content))

字符串匹配无法实现的—通配符

在正则表达式中,通配符有*和?,可以用他们来表示任何字符
比如要做到匹配zeng1.doc zengsf2.docx zengCV.txt,用字符串函数比较难做到
但以下的正则表达式很容易匹配得到
#!/usr/bin/env python
# encoding: utf-8

import re

content = 'zeng1.doc zengsf2.docx zengCV.txt'
print(re.findall(r'zeng[1-9a-zA-Z]*\.[1-9a-zA-Z]*', content))

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值