正则表达式

正则表达式课程笔记

1、正则表达式概述

Regular Expression 缩写为regex, regexp, RE等,也可以叫规则表达式。是对字符串和特殊字符操作的一种逻辑。采用事先定义的字符串和字符组合,组成一个规则字符串来过滤逻辑。

2、用途

通常被用来检索、替换那些符合某个规则的文本。

3、具体实例(python中用法)

### match和search用法

#### import re 导入模块

“””
s = ”’The\nquick\nbrown\nfox\njumps\nover\na\nlazy\ndog”’
for x in s:
pass
result1 = re.match(‘T’,s)
result2 = re.match(‘h’,s) None
result3 = re.match(‘^q’,s,re.M) None
result4 = re.match(‘^b’,s,re.S) None
result5 = re.search(‘a’,s)
result6 = re.search(‘y’,s,re.M)

编译之后的匹配
regex = re.compile(‘f’)
result7 = regex.match(s) 还是从头找
result8 = regex.match(s,16) 位置刚好的时候可以找到
result9 = regex.search(s) 找到就返回,忽略单行和多行

print(result1,’\n’,result2,’\n’,result3,’\n’,result4,’\n’,result5,’\n’,result6,’\n’,result7,’\n’,result8,’\n’,result9)

输出结果为:
<_sre.SRE_Match object; span=(0, 1), match=’T’>
None
None
None
<_sre.SRE_Match object; span=(31, 32), match=’a’>
<_sre.SRE_Match object; span=(36, 37), match=’y’>
None
<_sre.SRE_Match object; span=(16, 17), match=’f’>
<_sre.SRE_Match object; span=(16, 17), match=’f’>
“”””

 

## 全部查找:

### findall的方法:

“””
import re
findall(pattern,string,flags=0)
对整个字符串,从左至右匹配,返回所有匹配项的列表
s = ”’The\nquick\nbrown\nfox\njumps\nover\na\nlazy\ndog”’
for x in s:
pass
result = re.findall(‘u’,s) 匹配到所有的u,然后返回一个所有匹配到u的列表
regex = re.compile(‘^T’) 如果把T换成后面的字母,会发现返回结果为空列表。
result1 = regex.findall(s) 把字符看成一个整体,返回一个空列表。
regex1 = re.compile(‘^b’,re.M)
result2 = regex1.findall(s) 多行模式可以找到
regex2 = re.compile(‘^b’,re.S) 单行模式无法找到,也就是说这个字符串被看成一个整体,返回空列表
result3 = regex2.findall(s)
regex3 = re.compile(‘o’,re.M)
result4 = regex3.findall(s,5,18) 如果限定了位置的话,只会找限定以内的,返回列表

print(result,result1,result2,result3,result4)

打印结果为:
[‘u’, ‘u’]
[‘T’]
[‘b’]
[]
[‘o’, ‘o’]
“””

 

#### finditer方法:

“””
import re
finditer(pattern,string,flags=0)
regex.finditer(string[,pos[,endpos]])
对整个字符串,从左至右匹配,返回所有匹配项,返回迭代器
需要注意的是每次返回的都match对象

s = ”’The\nquick\nbrown\nfox\njumps\nover\na\nlazy\ndog”’
for x in s:
pass
regex = re.compile(‘o’)
result = regex.finditer(s)
print(type(result)) 可调用的迭代对象
print(next(result)) 返回的结果是match对象
print(next(result)) 返回match对象

 

打印结果为:
<class ‘callable_iterator’>
<_sre.SRE_Match object; span=(12, 13), match=’o’>
<_sre.SRE_Match object; span=(17, 18), match=’o’>
“””

 

#### fullmatch方法

“””
s = ”’The\nquick\nbrown\nfox\njumps\nover\na\nlazy\ndog”’
for x in s:
pass
result = re.fullmatch(‘j’,s)

regex = re.compile(‘q’)
result1 = regex.fullmatch(s)
result2 = regex.fullmatch(s,4,5) 要完全匹配,多了少了都不行
result3 = regex.fullmatch(s,4)
print(result,’\n’,result1,’\n’,result2,’\n’,result3)

打印结果为:
None
None
<_sre.SRE_Match object; span=(4, 5), match=’q’>
None
“””

 

#### split用法:

“””
1、分割字符串
2、字符串的分割函数不怎么好用,不能指定多个分隔符进行分割。
3、re.split(pattern,string,maxsplit=0,flags=0)
4、re.split分割字符串

import re
s = ”’ 01 bottle 02 bag 03 big 200 apple”’

for x in s:
pass
把每行的单词都提取出来
print(s.split())

返回结果:[’01’, ‘bottle’, ’02’, ‘bag’, ’03’, ‘big’, ‘200’, ‘apple’]
发现若把单词提取出来,仅仅split是不行的

result = re.split(‘[\s\d]+’, s) 字符串首,正则空白或者数字至少重复一次(括号内,至少有一个空白或者数字)
print(result)

regex = re.compile(‘^[\s\d]+’) 字符串首
result1 = regex.split(s)
print(result1)

regex1 = re.compile(‘^[\s\d]+’,re.M)
result2 = regex1.split(s)
print(result2)

regex2 = re.compile(‘\s+\d+\s+’) 空白数字空白
result3 = regex2.split(‘ ‘+s) 因为都是字符串,所以可以直接相加
print(result3)

打印结果为:
[’01’, ‘bottle’, ’02’, ‘bag’, ’03’, ‘big’, ‘200’, ‘apple’]
[”, ‘bottle’, ‘bag’, ‘big’, ‘apple’]
[”, ‘bottle 02 bag 03 big 200 apple’]
[”, ‘bottle 02 bag 03 big 200 apple’]
[”, ‘bottle’, ‘bag’, ‘big’, ‘apple’]
“””

 

#### 匹配替换:

“””
re.sub(pattern,replacement,string,count=0,flags=0)
regex.sub(replacement,string,count=0)
使用pattern对字符串string进行匹配,对匹配项使用repl替换
replacement可以是string、bytes、function

re.subn(pattern,replacement,string,count=0,flags=0)
regex.subn(replacement,string,count=0)
同sub返回一个元组(new_string, number_of_subs_made)

import re
s = ”’bottle\nbag\nbig\napple”’
for x in s:
pass
替换方法
regex = re.compile(‘b\wg’)
result = regex.sub(‘Eric’, s)
print(result,end=”) 替换后返回结果是:bottle Eric Eric apple
result1 = regex.sub(‘telephone’, s, 1) 被替换1次
print(result1)

regex1 = re.compile(‘\s+’)
result2 = regex1.subn(‘ ‘, s)
print(result2) 返回一个元组和被替换的次数,(‘bottle bag big apple’, 3)

打印结果为:
bottle
Eric
Eric
applebottle
telephone
big
apple
(‘bottle bag big apple’, 3)
“””

 

#### 分组:

“””
使用分组把捕获到的数据放到了group中
match、search函数可以返回match对象;findall返回字符串列表;finditer返回一个个match对象
1、使用group(N)返回对应分组,1-N是对应分组,0返回整个匹配字符串
2、可以使用group(‘name’)取分组
3、使用groups()返回所有分组
4、使用groupdict()返回所有命名的分组

import re
s = ”’bottle\nbage\nbig\napple”’
for x in s:
pass
分组
regex = re.compile(‘(b\w+)’)
reuslt = regex.match(s)
print(1, type(reuslt))
print(2, ‘match’,reuslt.groups())
reuslt1 = regex.search(s,1) 限定匹配的起始位置
print(3, ‘search’, reuslt1.groups())

regex1 = re.compile(‘(b\w+)\\n(?P<name2>b\w+)\\n(?P<name3>b\w+)’) 这里转义不转义暂时测试没有影响
reuslt2 = regex1.match(s)
print(4, reuslt2, ‘match’)
print(5, reuslt2.group(3), reuslt2.group(2), reuslt2.group(1)) 这样打印报错:IndexError: no such group
print(5, reuslt2.group(‘name2’)) 造成上面报错的原因是打印的时候应该加上引号,因为名字为一个str(字符串)
print(type(‘name2’))
print(6, reuslt2.groupdict())

打印结果为:
1 <class ‘_sre.SRE_Match’>
2 match (‘bottle’,)
3 search (‘bage’,)
4 <_sre.SRE_Match object; span=(0, 15), match=’bottle\nbage\nbig’> match
5 bage
<class ‘str’>
6 {‘name2’: ‘bage’, ‘name3’: ‘big’}
“””

 

本文来自投稿,不代表Linux运维部落立场,如若转载,请注明出处:http://www.178linux.com/88221

赞 (1)
泰谷子泰谷子
上一篇 2017-11-04 20:54
下一篇 2017-11-05 16:35

相关推荐

  • 马哥教育网络班21期+第4周作业

    1、复制/etc/skel目录为/home/tuser1,要求/home/tuser1及其内部文件的属组和其它用户均没有任何访问权限。 [root@localhost ~]# cp -r /etc/skel /home/ && mv /home/skel&nbsp…

    Linux干货 2016-08-02
  • varnish学习总结

    什么是web cache?   Web缓存是指一个Web资源(如html页面,图片,js,数据等)存在与Web服务器和客户端(浏览器)直接的副本。缓存会根据进来的请求保存输出内容的副本;当下一个请求到来的时候,如果是相同的URL,缓存会根据缓存机制决定是直接使用副本响应访问请求还是向源服务器再次发送请求。       …

    Linux干货 2015-07-15
  • 马哥教育网络班21期-第7周课程练习

    第7周课程练习 创建一个10G分区,并格式为ext4文件系统; 添加一块硬盘sdb 要求其block大小为2048,       预留空间百分比为2, 卷标为MYDATA, 默认挂载属性包含acl; # mke2fs -t ext4 -b 2048 -L 'MYDATA' -m 2 # mount -o ac…

    Linux干货 2016-10-09
  • DHCP

    DHCP DHCP(Dynamic Host Configuration Protocol,动态主机配置协议)通常被应用在大型的局域网络环境中,主要作用是集中的管理、分配IP地址,使网络环境中的主机动态的获得IP地址、Gateway地址、DNS服务器地址等信息,并能够提升地址的使用率。 DHCP协议采用客户端/服务器模型,主机地址的动态分配任务由网络主机驱动…

    Linux干货 2016-11-07
  • Linux用户、组、权限管理

    Linux用户与组管理 Linux系统上,用户通过内核拷贝程序到内存中,从此发起进程。进程以发起者的身份进行,进程对文件的访问权限,取决于发起进程的用户的权限。而有些后台进程或服务类进程以非管理员身份运行,为此也需要创建多个普通用户,此类用户不需登录。 系统中,用户类别分为管理员和普通用户(系统用户和登录用户),组类别分为基本组和附加组。管理系统上的用户与组…

    Linux干货 2016-12-07
  • centos6的启动流程和grub实验

    一.centos的启动流程         post–mbr grub 1stage–stage1.5–stage 2 /boot/grub—/boot/grub/grub.conf —kernel /vmlinuz.XXX root=— /boo…

    2017-07-08