re模块 正则匹配

import re

re.M 多行模式 位或的意思

parrterm就是正则表达式的字符串,flags是选项,表达式需要被编译,通过语法、策划、分析后卫其编译为一种格式,与字符串之间进行转换

re模块

主要为了提速,re的其他方法为了提高效率都调用了编译方法,就是为了提速

re的方法

单次匹配

re.compile 和 re.match

def compile(pattern, flags=0):

return _compile(pattern, flags)

可看到,re最后返回的是_compile内部方法并对其进行转换

def match(pattern, string, flags=0):

return _compile(pattern, flags).match(string)

使用re模块

import re

s = ‘0123abc‘

regx = re.compile(‘\d‘)

print(type(regx))

print(re.match(regx,s))

<class ‘_sre.SRE_Pattern‘>

<_sre.SRE_Match object; span=(0, 1), match=‘0‘>

意思为返回一个模块为match

从头开始匹配扫描,发现匹配一次则不会再继续向下扫描执行

import re

s = ‘0123abc‘

regx = re.compile(‘\d‘)

matcher = re.match(‘\d‘,s)

#通过regex查看编译后的结果

print(matcher)

matcher.endpos

<_sre.SRE_Match object; span=(0, 1), match=‘0‘>

<class ‘_sre.SRE_Match‘>

每次运行的时候需要调用match

match内部调用了编译方法,意思是说明这个是内部函数,所以compile和match的处理方式是一样的

而match本质是从头向后匹配,找到立刻返回

s = ‘0123abc‘

regx = re.compile(‘[a|b]‘)

matcher = regx.match(s)

print(type(matcher))

print(matcher)

<class ‘NoneType‘>

None

发现是None,match要求必须是从头开始

改进:

s = ‘a0123abc‘

regx = re.compile(‘^[a|b]‘)

matcher = re.match(regx,s)

matcher = regx.match(s)

print(type(matcher))

print(matcher)

<class ‘_sre.SRE_Match‘>

<_sre.SRE_Match object; span=(0, 1), match=‘a‘>

编译后的match方法可以自己定义索引位置,但是compile没有

import re

s = ‘0123abc‘

regex = re.compile(‘[a|b]‘)

matcher = re.match(‘\d‘,s)

print(type(matcher))

print(matcher)

matcher = regex.match(s,2)

print(matcher)

<class ‘_sre.SRE_Match‘>

<_sre.SRE_Match object; span=(0, 1), match=‘a‘>

search 方法

import re

s = ‘012abc‘

mather = re.search(‘[ab]‘,s)

print(mather)

<_sre.SRE_Match object; span=(3, 4), match=‘a‘>

可看到已匹配到a

match和serach对比

match  找到第一个立即返回,位置是从3开始,直接打印,只匹配一次

search 不管从什么位置开始,找到第一个匹配的则立即返回,行为上和match差不多,只不过search是可以不定位置的

一般情况先都为先编译后使用,所以尽量少使用compile

有些情况也是第一次使用匹配的字符,所以如果明确开头是想要的,直接使用match,不然使用search频率比较高

fullmatch  全文匹配

fullmatch相当于正则匹配全场

import re

s = ‘0123abc‘

regx = re.compile(‘[ab]‘)

matcher = re.fullmatch(‘\w‘,s)

print(matcher)

matcher = regx.fullmatch(s)

print(matcher)

None

None

#改进:

matcher = regx.fullmatch(s,4,5)

print(matcher)

<_sre.SRE_Match object; span=(4, 5), match=‘a‘>

res = re.fullmatch(‘bag‘,s)

print(res)

None

由于fullmatch属于全文匹配,所以要么必须有范围,要么必须得知其长度

s = ‘‘‘bottle\nbag\nbig\nable‘‘‘

regex = re.compile(‘bag‘)

res = regex.fullmatch(s,7,10)        #匹配完全长度

print(res)

<_sre.SRE_Match object; span=(7, 10), match=‘bag‘>

使用全文匹配最好:

·尽量匹配字符

·先切片再匹配

每个字符对应索引不知,将索引获取后进行折行

s = ‘‘‘bottle\nbag\nbig\nable‘‘‘

for k in enumerate(s):

if k[0] % 8 == 0:

print()

print(k,end=‘ ‘)

findall

findall 所返回为一个列表

s = ‘0123abcd‘

regx = re.compile(‘^b\w+‘)

matcher = regx.findall(s,re.M)

print(type(matcher))

<class ‘list‘>

找到所有包含b的字符

s = ‘‘‘bottle\nbag\nbig\nable‘‘‘

rest = re.findall(‘b‘,s)

print(rest)

[‘b‘, ‘b‘, ‘b‘, ‘b‘]

s = ‘‘‘bottle\nbag\nbig\nable‘‘‘

regx = re.compile(‘^b‘)

rest = re.findall(regx,s)

print(rest)

[‘b‘]

import re

s = ‘‘‘bottle\nbag\nbig\nable‘‘‘

regx = re.compile(‘^b‘,re.M)

rest = re.findall(regx,s)

print(rest)

[‘b‘, ‘b‘, ‘b‘]

re.M

SRE_FLAG_MULTILINE = 8 # treat target as multiline string

最少匹配一个

s = ‘0123abcd‘

regex = re.compile(‘[ab]+‘)

matcher = regex.findall(s)    #字节调用regex方法后面跟字符串即可

print(matcher)

[‘ab‘]

匹配非数字所有的

s = ‘0123abcd‘

regex = re.compile(‘\D‘)

matcher = regex.findall(s)

print(matcher)

[‘a‘, ‘b‘, ‘c‘, ‘d‘]

finditer

返回一个可迭代对象

# coding:utf-8

import re

# s = ‘‘‘bottle\nbag\nbig\nable‘‘‘

s = ‘0123abcd‘

regex = re.compile(‘\D‘)

matcher = regex.findall(s)

print(matcher)

matcher = regex.finditer(s)

print(type(matcher))

print(matcher)

[‘a‘, ‘b‘, ‘c‘, ‘d‘]

<class ‘callable_iterator‘>

<callable_iterator object at 0x0000000000B87128>        #返回一个迭代器

迭代器可以使用next直接跑出来

for i in matcher:

print(i)

<_sre.SRE_Match object; span=(4, 5), match=‘a‘>

<_sre.SRE_Match object; span=(5, 6), match=‘b‘>

<_sre.SRE_Match object; span=(6, 7), match=‘c‘>

<_sre.SRE_Match object; span=(7, 8), match=‘d‘>

regex = re.compile(‘\D‘)

matcher = re.match(‘\d‘,s)

print(matcher.span())

(0, 1)

re.M 多行模式

import re

s = ‘‘‘bottle\nbag\nbig\nable‘‘‘

regex = re.compile(r‘^b\w+‘,re.M)

matcher = regex.findall(s)

print(matcher)

[‘bottle‘, ‘bag‘, ‘big‘]

去掉re.M查看

s = ‘‘‘bottle\nbag\nbig\nable‘‘‘

regex = re.compile(r‘^b\w+‘)

matcher = regex.findall(s)

print(matcher)

[‘bottle‘]

筛取以e结尾的行

import re

s = ‘‘‘bottle\nbag\nbig\nable‘‘‘

regex = re.compile(r‘^\w+e$‘,re.M)

matcher = regex.findall(s)

print(matcher)

为了避免出现问题,就用\n的方式进行分割

在边界的时候指定选项re.M

匹配并替换

sub

re.sub 匹配原来的字符并替换,可根据次数进行调整

将每个数字都替换为一个串字符

import re

s = ‘‘‘bottle\n123\nbag\nbig\nable‘‘‘

regx = re.compile(‘\d‘)

res = regx.sub(‘haha‘,s)

print(res)

bottle

hahahahahaha

bag

big

able

替换一次

res = regx.sub(‘haha‘,s,1)

haha23

将big bag 替换

s = ‘‘‘bottle\n123\nbag\nbig\nable‘‘‘

regx = re.compile(‘\w+g‘)

res = regx.sub(‘hh‘,s)

print(res)

返回了一个新的字符串

hh

hh

使用subn

s = ‘‘‘bottle\n123\nbag\nbig\nable‘‘‘

regx = re.compile(‘\w+g‘)

print(regx.subn(‘ha‘,s))

返回一个元组

(‘bottle\n123\nha\nha\nable‘, 2)

subn会将其全部封装至一个元组中

s = ‘‘‘os.path([path])‘‘‘

regx = re.compile(‘[.]‘)

print(type(regx))

print(regx)

<class ‘_sre.SRE_Pattern‘>

re.compile(‘[.]‘)

将其替换为空格

newstr = regx.sub(‘ ‘, s)

print(newstr)

newstr = regx.subn(‘ ‘, s)

print(newstr)

os path([path])

(‘os path([path])‘, 1)

字符串分割

re.split() 可匹配模式、字符串、最大切割数

s = ‘‘‘\

01 bottle

02 bag

03 big1

100 bale

‘‘‘

regx = re.compile(‘^[\s\d]+‘)

res = re.split(regx,s)

print(res)

[‘‘, ‘bottle\n02 bag\n03 big1\n100 bale\n‘]

如果想去掉\n 需要涉及到断言

数字之前是\n

regx = re.compile(‘\s+|(?<=!\w)\d‘)

res = re.split(regx,s)

print(res)

[‘01‘, ‘bottle‘, ‘02‘, ‘bag‘, ‘03‘, ‘big1‘, ‘100‘, ‘bale‘, ‘‘]

如果使用\d+的话,则数字也全部被消除

regx = re.compile(‘\s+|(?<!\w)\d+‘)

res = re.split(regx,s)

print(res)

[‘‘, ‘‘, ‘bottle‘, ‘‘, ‘‘, ‘bag‘, ‘‘, ‘‘, ‘big1‘, ‘‘, ‘‘, ‘bale‘, ‘‘]

筛出空格两边的数字

\s+\d+\s+

之前用的是断言方式,有点复杂,现在我们发现一个规律:两头都有空字符,除了第一行

对于023来讲,前有\n

所以认为数字两边都有空白字符的话,则直接匹配并替换

分组

使用小括号的模式捕获的数据存在了组中

match 、search函数可以返回match对象

findall返回字符串列表

finditer返回一个个的match对象

使用group(N)方式对应分组,1-N是对应的分组,0是返回整个字符串

使用group,在match对象中加入分组会返回一个group,返回一个>=0的整数,1代表1号分组 以此类推

import re

s = ‘‘‘\

01 bottle

02 bag

03 big1

100 bale

‘‘‘

import re

s = ‘‘‘bottle\nbag\nbig1\nbale‘‘‘

regex = re.compile(‘(b\wg)‘)

matcher = regex.search(s)

print(matcher)

print(matcher.groups())

<_sre.SRE_Match object; span=(13, 16), match=‘bag‘>

(‘bag‘,)

0位整个串,如果超出的话不会报错,一直都是0

print(matcher.groups(0))

print(matcher.groups(1))

print(matcher.groups(2))

print(matcher.groups(3))

(‘bag‘,)

(‘bag‘,)

(‘bag‘,)

(‘bag‘,)

更改\b开头,并以e结尾

regex = re.compile(‘(b\w+e)‘,re.M)

我们用的是search方法,所知匹配一次

查看:

0是表示匹配从b开头,,b不属于元组内,e也不是

regex = re.compile(‘b(\w+)e‘,re.M)

(‘ottl‘,)

替换为findall

import re

s = ‘‘‘bottle\nbag\nbig1\nbale‘‘‘

regex = re.compile(‘\b(\w+)e‘)

matcher = regex.findall(s)

print(matcher.groups(1))

提示:

意思为能匹配到,但是不能用列表的方式进行group(),需要自己处理

改进:

使用finditer,使用迭代器,进行循环

import re

s = ‘‘‘bottle\nbag\nbig1\nbale‘‘‘

regex = re.compile(‘\b(\w+)(e)‘)

matchers = regex.finditer(s)

print(matchers)

for matchers in matchers:

print(matchers.groups())

分组匹配的太多,我们仅需要将分组外的抛除

regex = re.compile(‘b(\w+) (?p<TAIL>e)‘)

groupdict

用命名则按照索引方式,用了名字照样可以用索引方式同时支持groupdict()

正则匹配练习

匹配邮箱地址

匹配邮箱地址

html标记获取文字

获取<a>标记

改进

更严谨的判断:

看到这里是\w不带等号或者引号

用取非的方式获取

更复杂的实现:

通过分组取出

改进:

如果取得属性,并有引号则用引号取边界并取反

如果url后面有属性参数可以改为:

匹配一个url

\S 一定不出现空格的字符并至少出现1次的,

匹配身份证

判断密码强弱

凡是有非法字符在的话则替换为空,这样会缩减,并判断字符串的长度

\W判断,查看是否有特殊符号,其他全是合法字符,这样的话肯定会扫描出非合法密码

获取别人最少用的_ 符号,也就是必包含它

单词统计

file_path = r‘C:\Users\Administrator\Desktop\sample.txt‘

s = ‘‘‘index modules | next | previous |  Python 3.5.3 Documentation The Python Standard Library 11. File and Directory Access ‘‘‘

regex = re.compile(‘[^-\w]+‘)

d = defaultdict(lambda:0)

with open(file_path,‘r+‘,encoding=‘utf-8‘) as f:

for line in f:

for x in re.split(regex,line):

if len(x) > 0:

d[x] += 1

print(sorted(d.items(),key=lambda x:x[1],reverse=True))

时间: 2024-08-25 16:22:20

re模块 正则匹配的相关文章

day6 反射,hashlib模块,正则匹配,冒泡,选择,插入排序

一.反射(自省) 首先通过一个例子来看一下本文中可能用到的对象和相关概念. import sys # 模块,sys指向这个模块对象import inspectdef foo(): pass # 函数,foo指向这个函数对象 class Cat(object): # 类,Cat指向这个类对象 def __init__(self, name='kitty'): self.name = name def sayHi(self): # 实例方法,sayHi指向这个方法对象,使用类或实例.sayHi访问

Python之re模块----正则匹配

正则的介绍及应用实例详解 """ 1.什么是正则 正则就是用一系列具有特殊含义的字符组成一套规则,该规则用来描述具有某一特征的字符串, 正则就是用来去一个大的字符串中匹配出符合规则的子字符串 2.为什么要用正则 1.用户注册 2.爬虫程序 3.如何用正则 """ import re #\w匹配字母数字下划线-----------\W匹配非字母数字下划线 print(re.findall('\w','hello 123_ */-=')) print

正则匹配

python中re模块 1.正则匹配基础知识 (1)通配符. .ython可以匹配 aython,jython,只有一个字符 如果要匹配a.py的话需要进行转义a\.py,r如果这样写a.py那么会匹配成aapy (2)字符集[] [a-z]ython 可以匹配a-z之间任意一个字符 yython [a-zA-Z0-9]ython 匹配a-z,A-Z,0-9的任意字符串 [^p]ython反转匹配,可以匹配除了python的字符串 (3)选择符 | python|perl匹配python和per

常用的re模块的正则匹配的表达式

07.01自我总结 常用的re模块的正则匹配的表达式 一.校验数字的表达式 1.数字 ^[0-9]\*$ 2.n位的数字 ^\d{n}$ 3.至少n位的数字 ^\d{n,}$ 4.m-n位的数字 ^\d{m,n}$ 5.零和非零开头的数字 ^(0|[1-9][0-9]\*)$ 6.非零开头的最多带两位小数的数字 ^([1-9][0-9]\*)+(\.[0-9]{1,2})?$ 7.带1-2位小数的正数或负数 ^(\-)?\d+(\.\d{1,2})$ 8.正数.负数.和小数 ^(\-|\+)?\

web爬虫,scrapy模块标签选择器下载图片,以及正则匹配标签

标签选择器对象 HtmlXPathSelector()创建标签选择器对象,参数接收response回调的html对象需要导入模块:from scrapy.selector import HtmlXPathSelector select()标签选择器方法,是HtmlXPathSelector里的一个方法,参数接收选择器规则,返回列表元素是一个标签对象 extract()获取到选择器过滤后的内容,返回列表元素是内容 选择器规则 //x 表示向下查找n层指定标签,如://div 表示查找所有div标签

php正则匹配用户名必须包含字母和数字且大于6位

php正则匹配用户名必须包含字母和数字且大于6位 UEditor 1.4.3版本中去掉本地自动保存功能 右键菜单没有新建文本文档txt 常见HTTP错误代码大全 http常见状态码 eclipse内存溢出错误 为什么井盖是圆的?--揭开面试题的神秘面目! Linux Centos 6.6搭建SFTP服务器 密码强度检测 JS判断检测用户输入密码强度代码 对程序员来说,提高薪水最好的建议是什么? CSS3仿淘宝右侧固定导航悬浮层 jQuery仿淘宝网登录拖动滑块验证码代码 jQuery单击div更

Python使用re模块正则式的预编译及pickle方案

项目上线要求当中有言论和昵称的过滤需求, 客户端使用的是python脚本, python脚本中直接利用re模块来进行正则匹配, 一开始的做法是开启游戏后, 每帧编译2条正则式, 无奈运营需求里面100+条略为复杂的正则式, 一条编译起来在pc上都需要80ms, 造成客户端开启时候的卡顿. 解决方案当然是保存re模块编译的正则式结果, 之后开机直接加载就行, 然而需要注意的是re.compile()返回的_sre.SRE_Pattern对象虽然可以使用pickle保存下来, 但是这只是个假象, 实

Python正则匹配字母大小写不敏感在读xml中的应用

需要解决的问题:要匹配字符串,字符串中字母的大小写不确定,如何匹配? 问题出现之前是使用字符串比较的方式,比如要匹配'abc',则用语句: 1 if s == 'abc':#s为需要匹配的字符串 2 print '匹配成功\n' 现在的问题是s可能是Abc.ABC等等,所以需要大小写不敏感的匹配,如果把需要匹配的模式的大小写进行罗列,那即使是三个字母的短模式也是很麻烦,查了一下,正则表达式re模块中有个参数flags=re.I,这样就可以大小写不敏感的匹配了,示例如下: 1 import re

python 爬蟲 解析/正则匹配/乱码问题整理

今日爬取一听/扬天音乐都遇到了某些问题,现在对爬取过程中遇到的问题,做对于自己而言较为系统的补充与解释.主要问题有一下几点: 一:beautiful,urllib等库进行网页解析时,对于目标下的东西无法进行解析与显示 二:正则匹配虽然看过许多,但实际使用时仍然不够熟练,需要大量参考,故而,打算重新整理 三:对于乱码问题,曾在建mysql数据库时,头疼多次,现打算对于网页解析的乱码处理方法做些整理 这次目标是爬取扬天音乐"http://up.mcyt.net/",需要获取的内容有:歌曲名