python regex module re 使用

reference regex module in python

import re

re.search

re.search(regex, subject, regex_matching_mode): apply a regex pettern to a subject string(with a specified searching mode)

searching mode: re.I(re.IGNORECASE) , re.S(re.DOTALL), re.M(re.MULTLINE) 可以使用 | 来使用多种mode e.g. re.I | re.S 。 re.L(re.LOCALE) re.U(re.UNICODE): 主要用于修改\w 对应word_characters 的范围

return None if matching attempt fails and a Match object otherwise

因为None 与False 等价 所以可以被用在 if statement

其他类似的function(不支持 regex matching flags)

re.match(regex, subject): re.search 遍历整个字符串来进行匹配,而re.match 只在字符串的开头寻找匹配 re.match("regex", subject) is equal to re.search("\Aregex", subject)

re.fullmatch(regex, subject): 只有在 subject与regex完全匹配时,return Match object, otherwise None (which is equal to re.search("\Aregex\Z", subject))

re.findall(regex, subject: This will return an array of all non-overlapping regex matches in the string. 当 存在一个或者多个capturing groups时, return a array of tuple

re.finditer(regex, subject): return a iterator(more effcient than re.findall()) 返回一个由match object组成的迭代器

for m in re.finditer(regex, subject)

#  ordinary character
# r"" raw string literal
subject = "Hello_world_hello"
regex_1 = r"Hello"
regex_2 = r"World"

if re.search(regex_1, subject, flags=re.I):
print('Match')
else:
print('Not a match') if re.search(regex_2, subject, flags=re.I):
print('Match')
else:
print('Not a match') if re.search(regex_1, subject):
print('Match')
else:
print('Not a match') if re.search(regex_2, subject):
print('Match')
else:
print('Not a match')
Match
Match
Match
Not a match

Match Details(关于匹配的细节)

re.search 和 re.match return a Match object ; re.finditer 生成一个迭代器用于遍历 Match object

Match object(using m to signify it) 包含关于match 的许多有用的信息

m.group(): returns the part of the string matched by the entire regular expression,即返回被整个正则表达式所匹配的部分

m.start(): returns the offset in the string of the start of the match ,返回匹配位置的偏移量

m.end():returns the offset of the character beyond the match, 返回match之后character的偏移量

m.span() : tuple(m.start(), m.end())

可以使用 m.start() 与 m.end() 进行切片, subject[m.start(): m.end()]

如果想要指定capturing_group 匹配的结果, e.g. m.group(group_number) m.group(group_name)

如果想要做搜索替换 而不调用 re.sub() 那么可以使用 m.expand(replacement) 去计算替换的结果

注意

re.search search throughout the string until find a match

re.match attempts the pattern at the very start of the string until find a match

re.findall and re.finditer will find all the matches

# the match details
m = re.search(regex_1, subject, flags=re.I)
print(f'regex {regex_1}')
print(f'subject {subject}')
print(f"m.group: {m.group()}")
print(f"m.start: {m.start()}")
print(f"m.end: {m.end()}")
print(f"m.span: {m.span()}")
print(subject[m.start():m.end()])
regex   Hello
subject Hello_world_hello
m.group: Hello
m.start: 0
m.end: 5
m.span: (0, 5)
Hello
# finditer
for m in re.finditer(r'(?i)' + regex_1, subject):
print(m.span())
print(subject[m.start(): m.end()])
(0, 5)
Hello
(12, 17)
hello
# findall
print(re.findall(r'(?i)' + regex_1, subject))
print(type( re.findall(r'(?i)' + regex_1, subject) ))
['Hello', 'hello']
<class 'list'>

Strings , Backslashes and Regular Expressions

regex 使用 反斜杠进行转义特殊字符, 而python字符串中也使用反斜杠进行转义字符。 因此\\ 在正则表达式中为一个literal backslash 对应的python字符串 为 \\\\ 不便于阅读

因此采用 python 的 raw string 特性 r"\\" 对于字符串去转义, 以简化 正则表达式的书写

regex_non_raw = '\\\\'
regex_raw = r'\\' literal_backblash = r'\abc' if re.search(regex_non_raw, literal_backblash):
print('Match')
else:
print('not a Match') if re.search(regex_raw, literal_backblash):
print('Match')
else:
print('not a Match')
Match
Match

Unicode

关于 Unicode notation \uFFFF

为了避免关于反斜杠是否应该被转义的困惑, 我们应该使用 raw Unicode string ur"\uFFFF\d"(当然前缀u并不必要)

print(u'\uEFFFa')
a

Search and Replace

查找替换的实现

re.sub(regex, replacement, subject): replacing all matches of regex in subject with replacement。

return the result of modified(the subject is not modified)

如果regex有 capturing groups, 可以使用 \g \number 来指定替换的group

result = re.sub(regex_1, 'world', subject, flags= re.I)
result_with_constrained_times = re.sub(regex_1, 'world', subject, count=1) print(f'replace all match : {result}')
print(f'replace match according to specified times : {result_with_constrained_times}')
replace all match :   world_world_world
replace match according to specified times : world_world_hello

Splitting Strings

re.split(regex, subject, control_the_number_of_splits): 根据 regex matches 将字符串进行切分

return a array of string(the matches is not included in the result but the capturing_groups is included in the result)

target = re.split(regex_1, subject, flags=re.I)
target_with_contrained_times = re.split(regex_1, subject, maxsplit=1, flags=re.I) print(f"split_result_without_limit: {target}")
print(f"split_result_with_limit: {target_with_contrained_times}")
split_result_without_limit:    ['', '_world_', '']
split_result_with_limit: ['', '_world_hello']

Regex Objects

如果想要多次使用同一个正则表达式, 那么需要将其编译为一个 regular expression object

re.compile(regex) or re.compile(regex, flags): flags switch the matching mode

return regular expression object(regex_object)

regex_object 可以使用re库的所有函数

e.g.

re.compile.search(subject) == re.search(regex, subject)

re_object = re.compile(regex_1, flags=re.I)
print(re_object.findall(subject))
['Hello', 'hello']

总结

以上就是python正则表达式module re 的常用接口以及其与正则表达式之间的关系

以上内容中缺少 grouping_and_capturing 这一部分,并没有展示在存在capturing group时上述函数接口的表现,仅仅介绍了相关内容

进一步进阶使用时,主要体现在提升正则表达式的复杂度上,在这个notebook中只展示了 使用literal_text 进行匹配的结果

正则表达式快速入门二 :python re module 常用API介绍的更多相关文章

  1. 前端学习 node 快速入门 系列 —— 模块(module)

    其他章节请看: 前端学习 node 快速入门 系列 模块(module) 模块的导入 核心模块 在 初步认识 node 这篇文章中,我们在读文件的例子中用到了 require('fs'),在写最简单的 ...

  2. python基础31[常用模块介绍]

    python基础31[常用模块介绍]   python除了关键字(keywords)和内置的类型和函数(builtins),更多的功能是通过libraries(即modules)来提供的. 常用的li ...

  3. IdentityServer4 中文文档 -9- (快速入门)使用客户端凭证保护API

    IdentityServer4 中文文档 -9- (快速入门)使用客户端凭证保护API 原文:http://docs.identityserver.io/en/release/quickstarts/ ...

  4. Jupyter 快速入门——写python项目博客非常有用!!!

    from:https://blog.csdn.net/m0_37338590/article/details/78862488 一.简介: Jupyter Notebook(此前被称为 IPython ...

  5. python3.5+django2.0快速入门(二)

    昨天写了python3.5+django2.0快速入门(一)今天将讲解配置数据库,创建模型,还有admin的后台管理. 配置数据库 我们打开mysite/mysite/settings.py这个文件. ...

  6. C#正则表达式快速入门

    作者将自己在学习正则表达式中的心得和笔记作了个总结性文章,希望对初学C#正则表达式的读者有帮助. [内容] 什么是正则表达式 涉及的基本的类 正则表达式基础知识 构建表达式基本方法 编写一个检验程序 ...

  7. 小D课堂 - 零基础入门SpringBoot2.X到实战_第1节零基础快速入门SpringBoot2.0_1、SpringBoot2.x课程介绍和高手系列知识点

    1 ======================1.零基础快速入门SpringBoot2.0 5节课 =========================== 1.SpringBoot2.x课程全套介绍 ...

  8. 二、robotframework接口测试-常用关键字介绍

    1.常用关键字介绍: a. 打印:log                                                  用法:log   打印内容 ---------------- ...

  9. 小程序常用API介绍

    小程序常用API接口  wx.request https网络请求 wx.request({ url: 'test.php', //仅为示例,并非真实的接口地址 method:"GET&qu ...

  10. pip快速下载安装python 模块module

    g刚开始学习python时,每次想要安装某个module,都到处找module的安装包(exe.whl等) 装setuptools,然后在cmd里用easy_install装pip,然后用pip装你要 ...

随机推荐

  1. web自动化07-元素等待

    元素等待   1.什么是元素等待?       在定位页面元素时如果没找到,会在指定时间内一直等待的过程   2.为什么需要元素等待  网络速度慢  电脑配置低  服务器处理请求慢   3.三种元素等 ...

  2. 美女同事的烦恼:如何配置 Apache SkyWalking 告警?

    小婉 技术部基本上是一个和尚庙,女生非常少,即使有女生也略微有点抽象,小婉就不一样,她气质绝佳. 上午,同事小婉刚才从老板办公室里出来,看上去一脸不悦的样子.为了表示对同事的关(ba)心(gua),我 ...

  3. LeetCode 周赛 348(2023/06/05)数位 DP 模板学会了吗

    本文已收录到 AndroidFamily,技术和职场问题,请关注公众号 [彭旭锐] 加入知识星球提问! 往期回顾:LeetCode 单周赛第 347 场 · 二维空间上的 LIS 最长递增子序列问题 ...

  4. 【LeetCode滑动窗口专题#2】无重复字符的最长子串

    #1传送门 无重复字符的最长子串 给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串 的长度. 示例 1: 输入: s = "abcabcbb" 输出: 3 解释: 因为 ...

  5. 流程挖掘里程碑:国产RPA首次入选顶级行业报告

    正在成为组织运营标配的流程挖掘,到底有哪些商业价值? 作为超级自动化的重要先驱,流程挖掘正在成为组织运营标配 文/王吉伟 AIGC正在影响越来越多的行业,流程挖掘领域亦不例外. Mindzie首先宣布 ...

  6. ARC118E Avoid Permutations

    题意 给定一个长度为 \(n\) 的排列 \(p\),在一个 \((n + 2)\times(n + 2)\) 的网格上,禁止通过 \((i, p_i)\) 这些点,每次只能向上或右走一格,从 \(( ...

  7. 一文掌握设计模式(定义+UML类图+应用)

    一.引子 从学编程一开始就被告知,要想做一名优秀的程序员两大必要技能:1.源码阅读(JDK.C等底层语言封装) 2.设计模式(使用某种语言优雅的落地典型场景功能).一般随着工作年限的增长,被迫对底层语 ...

  8. Vue-CoreVideoPlayer 视频播放器组件

    安装 cnpm install -S vue-core-video-player 快速使用 # 在main.js中 import VueCoreVideoPlayer from 'vue-core-v ...

  9. 怎样优雅地增删查改(一):从0开始搭建Volo.Abp项目

    @ 目录 项目介绍 模块化 由框架实现的 需要实现的 创建项目 创建业务模块 配置引用和依赖 配置DbContext 创建实体和Dto 配置AutoMapper 软件系统中数据库或者持久层的基本操作功 ...

  10. Stable Diffusion AIGC:3步成为P图大师

    摘要:instructPix2Pix文字编辑图片是一种纯文本编辑图像的方法,用户提供一张图片和文本编辑指令,告诉模型要做什么,模型根据编辑指令编辑输入的图像,最终输出用户想要的图像. 本文分享自华为云 ...