Python3中正则模块re.compile、re.match及re.search函数用法

re模块 re.compile、re.match、 re.search

正则匹配的时候,第一个字符是 r,表示 raw string 原生字符,意在声明字符串中间的特殊字符不用转义。

比如表示 ‘\n',可以写 r'\n',或者不适用原生字符 ‘\n'。

推荐使用 re.match

re.compile() 函数

编译正则表达式模式,返回一个对象。可以把常用的正则表达式编译成正则表达式对象,方便后续调用及提高效率。

re.compile(pattern, flags=0)
  • pattern 指定编译时的表达式字符串
  • flags 编译标志位,用来修改正则表达式的匹配方式。支持 re.L|re.M 同时匹配

flags 标志位参数

re.I(re.IGNORECASE) 
使匹配对大小写不敏感

re.L(re.LOCAL)  
做本地化识别(locale-aware)匹配

re.M(re.MULTILINE)  
多行匹配,影响 ^ 和 $

re.S(re.DOTALL) 
使 . 匹配包括换行在内的所有字符

re.U(re.UNICODE)
根据Unicode字符集解析字符。这个标志影响 \w, \W, \b, \B.

re.X(re.VERBOSE)
该标志通过给予你更灵活的格式以便你将正则表达式写得更易于理解。

示例:

 import re
content = 'Citizen wang , always fall in love with neighbour,WANG'
rr = re.compile(r'wan\w', re.I) # 不区分大小写
print(type(rr))
a = rr.findall(content)
print(type(a))
print(a)

findall 返回的是一个 list 对象

<class '_sre.SRE_Pattern'>
<class 'list'>
['wang', 'WANG']

re.match() 函数

总是从字符串‘开头曲匹配',并返回匹配的字符串的 match 对象 <class '_sre.SRE_Match'>。

re.match(pattern, string[, flags=0])
  • pattern 匹配模式,由 re.compile 获得
  • string 需要匹配的字符串
 import re
pattern = re.compile(r'hello')
a = re.match(pattern, 'hello world')
b = re.match(pattern, 'world hello')
c = re.match(pattern, 'hell')
d = re.match(pattern, 'hello ')
if a:
print(a.group())
else:
print('a 失败')
if b:
print(b.group())
else:
print('b 失败')
if c:
print(c.group())
else:
print('c 失败')
if d:
print(d.group())
else:
print('d 失败')

运行结果:

hello
b 失败
c 失败
hello

match 的方法和属性

参考链接

 import re
str = 'hello world! hello python'
pattern = re.compile(r'(?P<first>hell\w)(?P<symbol>\s)(?P<last>.*ld!)') # 分组,0 组是整个 hello world!, 1组 hello,2组 ld!
match = re.match(pattern, str)
print('group 0:', match.group(0)) # 匹配 0 组,整个字符串
print('group 1:', match.group(1)) # 匹配第一组,hello
print('group 2:', match.group(2)) # 匹配第二组,空格
print('group 3:', match.group(3)) # 匹配第三组,ld!
print('groups:', match.groups()) # groups 方法,返回一个包含所有分组匹配的元组
print('start 0:', match.start(0), 'end 0:', match.end(0)) # 整个匹配开始和结束的索引值
print('start 1:', match.start(1), 'end 1:', match.end(1)) # 第一组开始和结束的索引值
print('start 2:', match.start(1), 'end 2:', match.end(2)) # 第二组开始和结束的索引值
print('pos 开始于:', match.pos)
print('endpos 结束于:', match.endpos) # string 的长度
print('lastgroup 最后一个被捕获的分组的名字:', match.lastgroup)
print('lastindex 最后一个分组在文本中的索引:', match.lastindex)
print('string 匹配时候使用的文本:', match.string)
print('re 匹配时候使用的 Pattern 对象:', match.re)
print('span 返回分组匹配的 index (start(group),end(group)):', match.span(2))

运行结果:

 group 0: hello world!
group 1: hello
group 2:
group 3: world!
groups: ('hello', ' ', 'world!')
start 0: 0 end 0: 12
start 1: 0 end 1: 5
start 2: 0 end 2: 6
pos 开始于: 0
endpos 结束于: 25
lastgroup 最后一个被捕获的分组的名字: last
lastindex 最后一个分组在文本中的索引: 3
string 匹配时候使用的文本: hello world! hello python
re 匹配时候使用的 Pattern 对象: re.compile('(?P<first>hell\\w)(?P<symbol>\\s)(?P<last>.*ld!)')
span 返回分组匹配的 index (start(group),end(group)): (5, 6)

re.search 函数

对整个字符串进行搜索匹配,返回第一个匹配的字符串的 match 对象。

re.search(pattern, string[, flags=0])
  • pattern 匹配模式,由 re.compile 获得
  • string 需要匹配的字符串
     import re
    str = 'say hello world! hello python'
    pattern = re.compile(r'(?P<first>hell\w)(?P<symbol>\s)(?P<last>.*ld!)') # 分组,0 组是整个 hello world!, 1组 hello,2组 ld!
    search = re.search(pattern, str)
    print('group 0:', search.group(0)) # 匹配 0 组,整个字符串
    print('group 1:', search.group(1)) # 匹配第一组,hello
    print('group 2:', search.group(2)) # 匹配第二组,空格
    print('group 3:', search.group(3)) # 匹配第三组,ld!
    print('groups:', search.groups()) # groups 方法,返回一个包含所有分组匹配的元组
    print('start 0:', search.start(0), 'end 0:', search.end(0)) # 整个匹配开始和结束的索引值
    print('start 1:', search.start(1), 'end 1:', search.end(1)) # 第一组开始和结束的索引值
    print('start 2:', search.start(1), 'end 2:', search.end(2)) # 第二组开始和结束的索引值
    print('pos 开始于:', search.pos)
    print('endpos 结束于:', search.endpos) # string 的长度
    print('lastgroup 最后一个被捕获的分组的名字:', search.lastgroup)
    print('lastindex 最后一个分组在文本中的索引:', search.lastindex)
    print('string 匹配时候使用的文本:', search.string)
    print('re 匹配时候使用的 Pattern 对象:', search.re)
    print('span 返回分组匹配的 index (start(group),end(group)):', search.span(2))

    注意 re.search 和 re.match 匹配的 str 的区别

运行结果:

 group 0: hello world!
group 1: hello
group 2:
group 3: world!
groups: ('hello', ' ', 'world!')
start 0: 4 end 0: 16
start 1: 4 end 1: 9
start 2: 4 end 2: 10
pos 开始于: 0
endpos 结束于: 29
lastgroup 最后一个被捕获的分组的名字: last
lastindex 最后一个分组在文本中的索引: 3
string 匹配时候使用的文本: say hello world! hello python
re 匹配时候使用的 Pattern 对象: re.compile('(?P<first>hell\\w)(?P<symbol>\\s)(?P<last>.*ld!)')
span 返回分组匹配的 index (start(group),end(group)): (9, 10)

PS:这里再为大家提供2款非常方便的正则表达式工具供大家参考使用:

JavaScript正则表达式在线测试工具:
http://tools.jb51.net/regex/javascript

正则表达式在线生成工具:
http://tools.jb51.net/regex/create_reg

更多关于Python相关内容可查看本站专题:《Python正则表达式用法总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

Python3中正则模块re.compile、re.match及re.search函数用法详解的更多相关文章

  1. SQL中CONVERT()函数用法详解

    SQL中CONVERT函数格式: CONVERT(data_type,expression[,style]) 参数说明: expression 是任何有效的 Microsoft® SQL Server ...

  2. php中setcookie函数用法详解(转)

    php中setcookie函数用法详解:        php手册中对setcookie函数讲解的不是很清楚,下面是我做的一些整理,欢迎提出意见.        语法:        bool set ...

  3. delphi中Application.MessageBox函数用法详解

    delphi中Application.MessageBox函数用法详解 Application.MessageBox是TApplication的成员函数,声明如下:functionTApplicati ...

  4. Python中正则模块re.compile、re.match及re.search函数用法

    import rehelp(re.compile)'''输出结果为:Help on function compile in module re: compile(pattern, flags=0) C ...

  5. Python3正则匹配re.split,re.finditer及re.findall函数用法详解

    这篇文章主要介绍了Python3正则匹配re.split,re.finditer及re.findall函数用法,结合实例形式详细分析了正则匹配re.split,re.finditer及re.finda ...

  6. mybatis中的mapper接口文件以及example类的实例函数以及详解

    ##Example example = new ##Example(); example.setOrderByClause("字段名 ASC"); //升序排列,desc为降序排列 ...

  7. php中fopen函数用法详解(打开文件)

    介绍下php中的fopen函数. 1.resource  fopen(string  $filename, string $mode [,bool $use_include_path [, resou ...

  8. IDL中File_Search函数用法详解(转)

    来自:http://blog.sina.com.cn/s/blog_764b1e9d01014ajp.html 在利用IDL进行批处理时,通常用到file_search函数进行输入路径文件的搜索,现根 ...

  9. JavaScript中bind、call、apply函数用法详解

    在给我们项目组的其他程序介绍 js 的时候,我准备了很多的内容,但看起来效果不大,果然光讲还是不行的,必须动手.前几天有人问我关于代码里 call() 函数的用法,我让他去看书,这里推荐用js 写服务 ...

随机推荐

  1. MVC框架以及实例

    MVC框架 MVC(model,view,controller),一种将业务逻辑.数据.界面分离的方法组织代码的框架.在改进界面及用户交互的同时,不需要重写业务逻辑.MVC将传统的输入.处理和输出分离 ...

  2. 微软在WPC 2015中为“伙伴们”带来了什么?

    在微软 WPC 2015(微软全球合作伙伴大会)上,微软全球渠道总监 Phil Sorgen 指出,微软总营收的 92% 来自合作伙伴.这句话验证了微软与合作伙伴间日益紧密的合作关系,也点出了本次大会 ...

  3. 简说mvc路由

    首先我们通过在Global.asax中的Application_Start将路由信息注册到RouteTable的Routes静态属性中.如下代码所示: public class RouteTable ...

  4. ext3 转 ext4 操作

    先关闭相关服务 cd / umount /dev/vg_nosql/nosql tune2fs -O has_journal,extents,huge_file,flex_bg,uninit_bg,d ...

  5. 9、django

    django是一款功能强大的web框架 自带admin后台管理.session.ORM.form验证功能.用户auth验证.模板引擎.simple tag.过滤器 Django RESTful fra ...

  6. 网站url常见报错

    报错情况比较复杂,此处列出比较常见的几种报错内容: 报错: 报错是一个大类, 的报错基本上是权限问题,出现 报错时您需要检测权限配置问题. 403.1 错误是由于“执行”访问被禁止而造成的.若试图从目 ...

  7. [T-ARA][Roly Poly]

    歌词来源:http://music.163.com/#/song?id=22704441 作曲 : 新沙洞老虎/崔圭成 [作曲 : 新沙洞老虎/崔圭成] [作曲 : 新沙洞老虎/崔圭成] 作词 : 新 ...

  8. Spring配置文件中的parent与abstract

    在看项目的Spring配置文件时,发现消息队列的配置采用了继承方式配置Bean,在这梳理总结一下. 其实在基于spring框架开发的项目中,如果有多个bean都是一个类的实例,如配置多个数据源时,大部 ...

  9. int vs Integer

    在项目开发过程中,有时候在选择int还是Integer会有些纠结.今天就来聊一下这个问题.当然,下面所说的基本也适用于java中其他基本类型和其包装类型. Definitions: int是原始类型, ...

  10. 问题:alias设置与删除

    新建alias条目 临时 alias  monitor='gnome-system-monitor' 永久 可以在家目录下,新建    .bash_aliases 文件,然后在其中加上你想要的替换的比 ...