python3 re返回形式总结

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

python3 re返回形式总结

小妮浅浅   2020-11-20 我要评论

我们在进行程序操作的时候,因为各种原因,需要通过不同的形式返回到之前的对象。不知道小伙伴们会几种返回的函数方法呢?今天要介绍的是findall和finditer这一对小伙伴,它们在输出的形式上有所不同。在这里小编先卖一个关子,想要知道答案的小伙伴,我们接着往下看。

findall(pattern, string, flags=0)

在字符串string中匹配所有符合正则表达式pattern的对象,并把这些对象通过列表list的形式返回。

import re
pattern = re.compile(r'\W+')
result1 = pattern.findall('hello world!')
result2 = pattern.findall('hello world!', 0, 7)
print(result1) #[' ', '!']
print(result2) #[' ']

finditer(pattern, string, flags=0)

在字符串string中匹配所有符合正则表达式pattern的对象,并把这些对象通过迭代器的形式返回。

import re
pattern = re.compile(r'\W+')
result = pattern.finditer('hello world!')
for r in result:
  print(r)
# <re.Match object; span=(5, 6), match=' '>
# <re.Match object; span=(11, 12), match='!'>

Python3 Re常用方法

常用的功能函数包括:compile、search、match、split、findall(finditer)、sub(subn)

1.compile

  • re.compile(pattern[, flags])

作用:把正则表达式语法转化成正则表达式对象

flags定义包括:

  • re.I:忽略大小写
  • re.L:表示特殊字符集 \w, \W, \b, \B, \s, \S 依赖于当前环境
  • re.M:多行模式
  • re.S:' . '并且包括换行符在内的任意字符(注意:' . '不包括换行符)
  • re.U: 表示特殊字符集 \w, \W, \b, \B, \d, \D, \s, \S 依赖于 Unicode 字符属性数据库

2.search

  • re.search(pattern, string[, flags])

作用:在字符串中查找匹配正则表达式模式的位置,返回 MatchObject 的实例,如果没有找到匹配的位置,则返回 None。

3.match

  • re.match(pattern, string[, flags])
  • match(string[, pos[, endpos]])

作用:match() 函数只在字符串的开始位置尝试匹配正则表达式,也就是只报告从位置 0 开始的匹配情况,

而 search() 函数是扫描整个字符串来查找匹配。如果想要搜索整个字符串来寻找匹配,应当用 search()。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们