正则表达式

正则表达式课程笔记

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

相关推荐

  • python练习实例

    #依次输出五位数的每一位(由低位到高位)i=12345for a in range(5):j=i%10i=i//10print(j) #依次输出五位数的每一位(由高位到低位)i=12345for a in range(5,0,-1):j=i//10**(a-1)i=i%10**(a-1)print(j) #打印菱形for i in range(-3,4):j…

    Linux干货 2018-03-25
  • linux磁盘管理及其磁盘分区工具的使用

    一、 几种分区工具: 1.图形化工具gnome-disks使用简单,在此不在赘述。 2.fdisk使用: fdisk支持MBR,也支持GPT分区,对于一块硬盘最多只能理解15个分区,一般使用fdisk做MBR分区,gdisk做GPT分区。下面为fdisk分区示例: [root@centos7 ~]# fdisk /dev/sde…

    Linux干货 2016-08-29
  • N25第一周博客作业

    本文主要阐述了以下几个知识点: l  计算机的组成及功能; l  介绍各不同发行版的linux及其联系; l  描述linux的哲学思想,及其本人对其个人理解; l  介绍一些linux基本命令及相关选项; l  如何在linux上使用帮助命令; l  罗列出发行版linux上的一些基础目录及其功用…

    Linux干货 2016-11-29
  • 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-10-30
  • 系统启动及恢复

    一、知识整理 1、modinfo命令:显示模块的详细描述信息: -n 只显示模块文件路径 -p 显示模块参数 -a auther -d description -l license协议 modprobe命令:装载或卸载内核 -r卸载内核,同rmmod 配置文件:/etc/modprobe.d/*.conf depmod命令:内核模块依赖关系文件及系统信息映射…

    Linux干货 2016-09-22
  • keepalive实验

    实验环境centos 7 server x2 做keepalived主备 地址分别是192.168.0.200 192.168.0.201 Centos 7 server x2 做real server 采用DR模型   yum -y install ntp#安装ntp client ntpdate 47.95.253.33#时间同步到自己的ntp…

    2017-12-11