正则表达式

正则表达式课程笔记

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

相关推荐

  • 第六周总结

    请详细总结vim编辑器的使用并完成以下练习题 vim: 模块化的编辑器   基本模式: 编辑模式,命令模式 输入模式 末行模式: 打开文件: # vim [options] [file..] +#:打开文件后,直接让光标处于第#行的行首; +/PATTERN:打开文件后,直接让光标处于第一个被PATTERN匹配到的行的行首; 模式转换: 编辑模式:…

    Linux干货 2017-08-07
  • HA Cluster:keepalived

    HA Cluster 集群类型:LB(lvs/nginx(http/upstream, stream/upstream))、HA、HP 系统可用性的公式:A=MTBF/(MTBF+MTTR) 系统故障: 硬件故障:设计缺陷、wear out、自然灾害 软件故障:设计缺陷 提升系统高用性的解决方案之降低MTTR: 解决方案:冗余(redundant) acti…

    Linux干货 2017-06-26
  • 第一周作业

    1、描述计算机的组成及其功能。
    2、按系列罗列Linux的发行版,并描述不同发行版之间的联系与区别。
    3、描述Linux的哲学思想,并按照自己的理解对其进行解释性描述。
    4、说明Linux系统上命令的使用格式;详细介绍ifconfig、echou、tty、startx、export、pwd、history、shutdown、poweroff、reboot、hwclock、date命令的使用,并配合相应的示例来阐述。
    5、如何在Linux系统上获取命令的帮助信息,请详细列出,并描述man文档的章节是如何划分的。
    6、请罗列Linux发行版的基础目录名称命名法则及共用规定。

    Linux干货 2017-12-03
  • 网络管理实战(子网划分、单网卡多IP、多网卡单IP、Linux路由实现)

        1、某公司申请到一个C 类IP 地址,但要连接6 个的子公司,最大的一个子 公司有26 台计算机,每个子公司在一个网段中,则子网掩码应设为?          分析过程:C类地址标准的掩码为24位,因为有6个子公…

    Linux干货 2016-09-05
  • Linux用户和组管理整理

    本节介绍Linux用户和组相关的配置文件,用户账号管理、查询用户信息以及切换用户的相关命令,将会让我们更了解各配置文件中各个字段的含义,以及各相关命令的使用方法,方便Linux运维人员管理Linux系统中的用户和组。 背景: Linux是个多用户、多任务的系统,考虑到每个人的隐私权、每个人喜好的工作环境以及每个用户所使用的权限等方面的不同,所以设定了“用户”…

    Linux干货 2015-06-15
  • 用户 组

    用户 组    在linux系统中,用户管理是基于用户名和密码的方式进行资源的分配,linux上用户Username/UID分为以下类别:    管理员: root,0    普通用户: 1-65535 普通用户分为:系统用户和登录用户两种 系统用户:1-499(cen…

    系统运维 2016-08-04