本文实例讲述了Python3中正则模块re.compile、re.match及re.search函数用法。分享给大家供大家参考,具体如下:

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

re 模块官方说明文档

正则匹配的时候,第一个字符是 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 对象

['wang', 'WANG']

re.match() 函数

总是从字符串‘开头曲匹配',并返回匹配的字符串的 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'(?Phell\w)(?P\s)(?P.*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('(?Phell\\w)(?P\\s)(?P.*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'(?Phell\w)(?P\s)(?P.*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('(?Phell\\w)(?P\\s)(?P.*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文件与目录操作技巧汇总》

希望本文所述对大家Python程序设计有所帮助。

本文标题: Python3中正则模块re.compile、re.match及re.search函数用法详解

本文地址: http://www.cppcns.com/jiaoben/python/230100.html

python中import re_Python3中正则模块re.compile、re.match及re.search函数用法详解相关推荐

  1. python中search用法_Python3中正则模块re.compile、re.match及re.search函数用法详解

    本文实例讲述了Python3中正则模块re.compile.re.match及re.search函数用法.分享给大家供大家参考,具体如下: re模块 re.compile.re.match. re.s ...

  2. python中mat函数_Python中flatten( )函数及函数用法详解

    flatten()函数用法 flatten是numpy.ndarray.flatten的一个函数,即返回一个一维数组. flatten只能适用于numpy对象,即array或者mat,普通的list列 ...

  3. python explode_pandas dataframe 中的explode函数用法详解

    在使用 pandas 进行数据分析的过程中,我们常常会遇到将一行数据展开成多行的需求,多么希望能有一个类似于 hive sql 中的 explode 函数. 这个函数如下: Code # !/usr/ ...

  4. python中isinstance怎么用_pythonisinstance函数用法详解

    这篇文章主要介绍了python isinstance函数用法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 isinstance() 函数来判断 ...

  5. python中setattr()函数用法详解

    setattr() 函数对应函数 getattr(),用于设置属性值,该属性不一定是存在的. getattr()用法详见博文:python中getattr()函数用法详解_IT之一小佬的博客-CSDN ...

  6. python中count的作用_python count函数用法详解

    在python中可以使用"count()"函数统计字符串里某个字符出现的次数,该函数用于统计次数,其语法是"count(sub, start= 0,end=len(str ...

  7. C++中substr()函数用法详解

    C++中substr()函数用法详解 原型: string substr (size_t pos = 0, size_t len = npos) const; 返回一个新构造的string对象,其值初 ...

  8. c++ memset 语言_C++中memset函数用法详解

    本文实例讲述了C++中memset函数用法.分享给大家供大家参考,具体如下: 功 能: 将s所指向的某一块内存中的每个字节的内容全部设置为ch指定的ASCII值,块的大小由第三个参数指定,这个函数通常 ...

  9. python lambda函数-Python的Lambda函数用法详解

    在Python中有两种函数,一种是def定义的函数,另一种是lambda函数,也就是大家常说的匿名函数.今天我就和大家聊聊lambda函数,在Python编程中,大家习惯将其称为表达式. 1.为什么要 ...

最新文章

  1. 2015大型互联网公司校招都开始了,薪资你准备好了嘛?
  2. win10软件拒绝访问删不掉_进程拒绝访问怎么结束_win10关闭进程拒绝访问的处理方法...
  3. R语言data.table导入数据实战:data.table中编写函数并使用SD数据对象
  4. android美颜功能,Android
  5. 《JavaScript高级程序设计》读书笔记(十一):内置对象Global
  6. jquery validation对隐藏的元素不进行验证
  7. html盒模型中border的写法,HTML+css盒子模型案例(圆,半圆等)“border-radius” 简单易上手...
  8. Hibernate框架 简述
  9. python两数相加有进退位_Leetcode_两数相加_python
  10. Google专卖店顾客消费预测问题:如何将数据的json格式转换成csv格式
  11. 1_线性表之顺序存储
  12. Java将视频文件、图片文件转Base64编码
  13. Unity3D贪吃蛇
  14. 基于SSM开发自行车在线租赁管理系统
  15. 完整的连接器设计手册_连接器退化机理是什么?(一)
  16. editormd生成博客编辑页面
  17. HC小区管理系统mysql如何修改密码
  18. excel快速填充_Excel教程:24秒,提取excel工作簿中300张图片
  19. 微信小程序-刷新当前页
  20. 大数据应用的几个实际案例

热门文章

  1. ASCLL码---阿斯科2码
  2. 如何使用swing创建一个BeatBox
  3. 中国云市场生变:华为云Q2份额超AWS,IaaS+PaaS迎来整体增长
  4. php代码审计文件包含,PHP代码审计之远程文件包含(RFI)
  5. 激活函数(sigmoid和ReLU)
  6. unity本地分数排行榜简单解决方案(Json)
  7. elementui表格在行内增删改查
  8. 设计模式——管道模式(一)
  9. 浙北山村“洋家乐”:中西结合乡村旅游成脱贫新产业
  10. 基于docker 搭建Prometheus+Grafana监控