python3 re返回形式总结

我们在进行程序操作的时候,因为各种原因,需要通过不同的形式返回到之前的对象。不知道小伙伴们会几种返回的函数方法呢?今天要介绍的是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)
# #

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()。

到此这篇关于python3 re返回形式总结的文章就介绍到这了。

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容