正则表达式

正则表达式课程笔记

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

相关推荐

  • N25-第二周博客作业

    第二周博客作业 1.Linux上的文件管理类命令都有哪些,其常用的使用方法和演示 2.bash的工作特性之命令执行状态返回值和命令行展开所涉及内容演示及其实例 3.请使用命令行展开功能完成以下练习;    (1)创建/tmp的目录下a_c,a_d,b_c,b_d     (2) 创建/tmp/mylinux目录下的 4…

    Linux干货 2016-12-11
  • 运维挖坑埋坑之旅—-413 Request Entity Too Large

    原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 、作者信息和本声明。否则将追究法律责任。http://nolinux.blog.51cto.com/4824967/1575160        好久没写博文了,天天忙的喘不过来气。最近是该总结总结前段时间的工作了,顺便缓解下这两天的霉…

    Linux干货 2016-08-15
  • shell脚本执行

    shell脚本执行 对于我们这些小白而讲,shell脚本无疑是最令人头疼的事了,我再这里讲一下shell脚本运行要注意的哪些。 shell脚本就好像c++,java代码一样,按照从上到下然后从左到右的顺序执行。就像我们日常读书一样。如果shell命令遇见了子进程(嵌套代码),程序就会跟着顺序进入子进程。当子进程完成后,回到父进程,并且把父进程所需要的参数提交…

    2017-06-05
  • httpd服务归纳:网络服务基础篇

    一、网络传输基础     1. 套接字:两类          1) Unix Sock: 一种本地文件系统          2) Socket: IP port (I…

    Linux干货 2015-05-04
  • 进程查看管理工具htop/dstat/top/ps

    ps:显示系统当前进程的运行情况         选项与参数(一):            a:所有与终端相关的进程;    x:所有与终端无关的进程;    u:以用户为中心组织进程状态信息显示;   &nb…

    2016-12-04
  • locate、find命令使用总结

    一、简介    在linux系统中存在"一切皆文件"的说法,这就足以说明文件的重要性,因此查找文件也是我们必须要掌握的技能。这时候熟练使用locate、find命令也就显得至关重要。尤其是find命令常用于日常工作中如安装完某个软件之后要查看这些软件的安装配置路径,或是需要按指定条件直接查找我们需要操作的文件。因此更需…

    Linux干货 2015-08-31