Python正则表达式Regular Expression初探

目录

Regular

匹配规则

单字符匹配

 数量匹配

边界匹配

 分组匹配

贪婪与懒惰

原版说明

特殊字符

转义序列

模块方法

函数说明

匹配模式

常用匹配规则

1. 匹配出所有整数

2. 匹配11位且13开头的整数


Regular

Python的re模块提供了完整的正则表达式功能。正则表达式(Regular Expression)是一种强大的文本模式匹配工具,它能高效地进行查找、替换、分割等复杂字符串操作。

在Python中,通过 import re 即可引入这一神器。

匹配规则

单字符匹配

语法功能注意事项
.匹配除换行符(\n)以外,任意一个字符。\.匹配点本身
[]匹配[]中列举的字符,可以是很多单个,也可以范围范围写法例如[2-6],[“a”-”b”]
\d匹配数字,即0-9 
\D匹配非数字 
\s匹配空白,即空格、tab键 
\S匹配非空白 
\w匹配单词字符,即a-z,A-Z,0-9,_ 
\W匹配非单词字符 

 数量匹配

语法功能注意事项
*匹配前一个规则的字符出现0至无数次 
+匹配前一个规则的字符出现1至无数次 
匹配前一个规则的字符出现0次或1次 
{n}匹配前一个规则的字符出现n次 
{n,}匹配前一个规则的字符出现最少n次 
{m,n}匹配前一个规则的字符出现m到n次 

边界匹配

语法功能注意事项
^匹配字符串的开始放在子表达式前
$匹配字符串的结束放在子表达式后
\b匹配单词的开始或结束 
\B匹配不是单词开头或结束的位置 

 分组匹配

语法功能注意事项
|匹配左右任意一个表达式 
()将匹配的内容里一部分抠出来就用括号抠出的内容不止一个就放到元组里

贪婪与懒惰

语法功能注意事项
*?重复任意次尽可能少重复
+?重复1次或更多次尽可能少重复
??重复0次或一次尽可能少重复
{n,m}?重复nm尽可能少重复
{n,}?重复n次以上尽可能少重复

原版说明

特殊字符

    The special characters are:
        "."      Matches any character except a newline.
        "^"      Matches the start of the string.
        "$"      Matches the end of the string or just before the newline at
                 the end of the string.
        "*"      Matches 0 or more (greedy) repetitions of the preceding RE.
                 Greedy means that it will match as many repetitions as possible.
        "+"      Matches 1 or more (greedy) repetitions of the preceding RE.
        "?"      Matches 0 or 1 (greedy) of the preceding RE.
        *?,+?,?? Non-greedy versions of the previous three special characters.
        {m,n}    Matches from m to n repetitions of the preceding RE.
        {m,n}?   Non-greedy version of the above.
        "\\"     Either escapes special characters or signals a special sequence.
        []       Indicates a set of characters.
                 A "^" as the first character indicates a complementing set.
        "|"      A|B, creates an RE that will match either A or B.
        (...)    Matches the RE inside the parentheses.
                 The contents can be retrieved or matched later in the string.
        (?aiLmsux) The letters set the corresponding flags defined below.
        (?:...)  Non-grouping version of regular parentheses.
        (?P<name>...) The substring matched by the group is accessible by name.
        (?P=name)     Matches the text matched earlier by the group named name.
        (?#...)  A comment; ignored.
        (?=...)  Matches if ... matches next, but doesn't consume the string.
        (?!...)  Matches if ... doesn't match next.
        (?<=...) Matches if preceded by ... (must be fixed length).
        (?<!...) Matches if not preceded by ... (must be fixed length).
        (?(id/name)yes|no) Matches yes pattern if the group with id/name matched,
                           the (optional) no pattern otherwise.

转义序列

    The special sequences consist of "\\" and a character from the list
    below.  If the ordinary character is not on the list, then the
    resulting RE will match the second character.
        \number  Matches the contents of the group of the same number.
        \A       Matches only at the start of the string.
        \Z       Matches only at the end of the string.
        \b       Matches the empty string, but only at the start or end of a word.
        \B       Matches the empty string, but not at the start or end of a word.
        \d       Matches any decimal digit; equivalent to the set [0-9] in
                 bytes patterns or string patterns with the ASCII flag.
                 In string patterns without the ASCII flag, it will match the whole
                 range of Unicode digits.
        \D       Matches any non-digit character; equivalent to [^\d].
        \s       Matches any whitespace character; equivalent to [ \t\n\r\f\v] in
                 bytes patterns or string patterns with the ASCII flag.
                 In string patterns without the ASCII flag, it will match the whole
                 range of Unicode whitespace characters.
        \S       Matches any non-whitespace character; equivalent to [^\s].
        \w       Matches any alphanumeric character; equivalent to [a-zA-Z0-9_]
                 in bytes patterns or string patterns with the ASCII flag.
                 In string patterns without the ASCII flag, it will match the
                 range of Unicode alphanumeric characters (letters plus digits
                 plus underscore).
                 With LOCALE, it will match the set [0-9_] plus characters defined
                 as letters for the current locale.
        \W       Matches the complement of \w.
        \\       Matches a literal backslash.

模块方法

    This module exports the following functions:
        match     Match a regular expression pattern to the beginning of a string.
        fullmatch Match a regular expression pattern to all of a string.
        search    Search a string for the presence of a pattern.
        sub       Substitute occurrences of a pattern found in a string.
        subn      Same as sub, but also return the number of substitutions made.
        split     Split a string by the occurrences of a pattern.
        findall   Find all occurrences of a pattern in a string.
        finditer  Return an iterator yielding a Match object for each match.
        compile   Compile a pattern into a Pattern object.
        purge     Clear the regular expression cache.
        escape    Backslash all non-alphanumerics in a string.

函数说明

match(pattern, string, flags=0)
    Try to apply the pattern at the start of the string, returning
    a Match object, or None if no match was found.

fullmatch(pattern, string, flags=0)
    Try to apply the pattern to all of the string, returning
    a Match object, or None if no match was found.

search(pattern, string, flags=0)
    Scan through string looking for a match to the pattern, returning
    a Match object, or None if no match was found.

sub(pattern, repl, string, count=0, flags=0)
    Return the string obtained by replacing the leftmost
    non-overlapping occurrences of the pattern in string by the
    replacement repl.  repl can be either a string or a callable;
    if a string, backslash escapes in it are processed.  If it is
    a callable, it's passed the Match object and must return
    a replacement string to be used.

subn(pattern, repl, string, count=0, flags=0)
    Return a 2-tuple containing (new_string, number).
    new_string is the string obtained by replacing the leftmost
    non-overlapping occurrences of the pattern in the source
    string by the replacement repl.  number is the number of
    substitutions that were made. repl can be either a string or a
    callable; if a string, backslash escapes in it are processed.
    If it is a callable, it's passed the Match object and must
    return a replacement string to be used.

split(pattern, string, maxsplit=0, flags=0)
    Split the source string by the occurrences of the pattern,
    returning a list containing the resulting substrings.  If
    capturing parentheses are used in pattern, then the text of all
    groups in the pattern are also returned as part of the resulting
    list.  If maxsplit is nonzero, at most maxsplit splits occur,
    and the remainder of the string is returned as the final element
    of the list.

findall(pattern, string, flags=0)
    Return a list of all non-overlapping matches in the string.

    If one or more capturing groups are present in the pattern, return
    a list of groups; this will be a list of tuples if the pattern
    has more than one group.

    Empty matches are included in the result.

finditer(pattern, string, flags=0)
    Return an iterator over all non-overlapping matches in the
    string.  For each match, the iterator returns a Match object.

    Empty matches are included in the result.

compile(pattern, flags=0)
    Compile a regular expression pattern, returning a Pattern object.

purge()
    Clear the regular expression caches

escape(pattern)
    Escape special characters in a string.


匹配模式

    Each function other than purge and escape can take an optional 'flags' argument
    consisting of one or more of the following module constants, joined by "|".
    A, L, and U are mutually exclusive.
        A  ASCII       For string patterns, make \w, \W, \b, \B, \d, \D
                       match the corresponding ASCII character categories
                       (rather than the whole Unicode categories, which is the
                       default).
                       For bytes patterns, this flag is the only available
                       behaviour and needn't be specified.
        I  IGNORECASE  Perform case-insensitive matching.
        L  LOCALE      Make \w, \W, \b, \B, dependent on the current locale.
        M  MULTILINE   "^" matches the beginning of lines (after a newline)
                       as well as the string.
                       "$" matches the end of lines (before a newline) as well
                       as the end of the string.
        S  DOTALL      "." matches any character at all, including the newline.
        X  VERBOSE     Ignore whitespace and comments for nicer looking RE's.
        U  UNICODE     For compatibility only. Ignored for string patterns (it
                       is the default), and forbidden for bytes patterns.


常用匹配规则

掌握正则的关键是根据规则来编写匹配样式,下面列出一些常用的Regular pattern:

1. 匹配出所有整数

>>> import re
>>> pat = '\d+'
>>> txt = 'No.123;Tel:1396260000'
>>> re.findall(pat, txt)
['123', '1396260000']

2. 匹配11位且13开头的整数

注意r'13\d{9}',13开头余下的9位数字用\d{9}表示

>>> import re
>>> txt = '''
... 001:13962600001
... 002:1330626001
... 003:18962600002
... 004:13106260003
... 005:16605200006
... '''
>>> pat = r'13\d{9}'
>>> re.findall(pat, txt)
['13962600001', '13106260003']

......

素材收集中。。。。。。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/638285.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Win10升级Win11后卡顿了?

目录 关闭动画效果 任务栏居中改为居左 调整外观和性能 其他 当你看到最后&#xff0c;还知道哪些升级WIN11后必做的优化呢&#xff1f;欢迎在评论区分享出来&#xff01;❤️ win11上市目前也有一段时间了&#xff0c;想必很多大家都已经进行更新了。新的系统确实更加简洁…

安规电容的知识

1、常见安规电容有哪些&#xff1f; 一般我们所说的安规电容也就有两种&#xff0c;一种就是X安规电容&#xff08;X1/X2/X3安规电容&#xff09;&#xff0c;还有一种是Y电容&#xff08;最常见的是Y1和Y2安规电容&#xff09;。 2、x电容的位置 火线零线间的是X电容。x电容用…

Git将某个文件合并到指定分支

企业开发中&#xff0c;经常会单独拉分支去做自己的需求开发&#xff0c;但是某些时候一些公共的配置我们需要从主线pull&#xff0c;这时候整个分支merge显然不合适 1.切换至待合并文件的分支 git checkout <branch>2.将目标分支的单个文件合并到当前分支 git checkou…

力扣刷MySQL-第三弹(详细讲解)

&#x1f389;欢迎您来到我的MySQL基础复习专栏 ☆* o(≧▽≦)o *☆哈喽~我是小小恶斯法克&#x1f379; ✨博客主页&#xff1a;小小恶斯法克的博客 &#x1f388;该系列文章专栏&#xff1a;力扣刷题讲解-MySQL &#x1f379;文章作者技术和水平很有限&#xff0c;如果文中出…

JVM中的垃圾收集算法

标记-清除算法 首先标记出所有需要回收的对象&#xff0c;在标记完成后&#xff0c;统一回收掉所有被标记的对象&#xff0c;也可以反过来&#xff0c;标记存活的对象&#xff0c;统一回收所有未被标记的对象。标记过程就是对象是否属于垃圾的判定过程 缺点 第一个是执行效率…

C# 获取QQ会话聊天信息

目录 利用UIAutomation获取QQ会话聊天信息 效果 代码 目前遇到一个问题 其他解决办法 利用UIAutomation获取QQ会话聊天信息 效果 代码 AutomationElement window AutomationElement.FromHandle(get.WindowHwnd); AutomationElement QQMsgList window.FindFirst(Tr…

4.postman批量运行及json、cvs文件运行

一、批量运行collection 1.各个接口设置信息已保存&#xff0c;在collection中点击run collection 2.编辑并运行集合 集合运行时&#xff0c;单独上传图片时报错。需修改postman设置 二、csv文件运行 可新建记事本&#xff0c;输入测试数据&#xff0c;后另存为新的文本文件&…

Pytest 结合 Allure 生成测试报告

测试报告在项目中是至关重要的角色&#xff0c;一个好的测试报告&#xff1a; 可以体现测试人员的工作量&#xff1b; 开发人员可以从测试报告中了解缺陷的情况&#xff1b; 测试经理可以从测试报告中看到测试人员的执行情况及测试用例的覆盖率&#xff1b; 项目负责人可以通过…

echarts-wordcloud词云

echarts-wordcloud是基于echarts的一个插件&#xff0c;所以我们要首先安装echarts包&#xff0c;然后再安装echarts-wordcloud的包&#xff0c;这里我的练习项目安装的版本&#xff1b;当然&#xff0c;你可以随意安装你需要的版本&#xff1b; “echarts”: “^5.3.3”, “ec…

面试2024.1.20

简单介绍下你做的项目。 这个神领物流项目是一个前后端分离的项目&#xff0c;前段他有3个客户端&#xff08;用户端为微信小程序、司机端和快递员端为app&#xff09;一个管理端&#xff08;pc&#xff09;&#xff0c;后端用的技术栈用的是SpringAlibabaCloud、数据库用的是M…

【精选】中间件 tomcat漏洞复现

&#x1f36c; 博主介绍&#x1f468;‍&#x1f393; 博主介绍&#xff1a;大家好&#xff0c;我是 hacker-routing &#xff0c;很高兴认识大家~ ✨主攻领域&#xff1a;【渗透领域】【应急响应】 【python】 【VulnHub靶场复现】【面试分析】 &#x1f389;点赞➕评论➕收藏…

JRTP实时音视频传输(2)-使用TCP通信的案例

环境搭建等参考&#xff1a;JRTP实时音视频传输(1)-必做的环境搭建与demo测试 1.创建自己的demo 先将example1拷贝为myclienttcp.cpp和myservertcp.cpp cp example1.cpp myclienttcp.cpp cp example1.cpp myservertcp.cpp 改写jrtplib/JRTPLIB/examples/CMakeLists.txt&…

79、avx2 向量指令集优化卷积运算

上一节 介绍了 avx2 向量指令集中的 load/store 操作,本节介绍如何使用 avx2 的向量指令集来实现乘累加运算。 因为我们实战中用到的 resnet50 神经网络中,卷积运算在整个模型中的比例占据是相当高,而卷积运算的核心计算就是乘累加计算。因此,只要将最核心的乘累加计算效率…

怎么从视频中提取动图?一个方法快速提取gif

视频以连续的方式播放一系列图像帧&#xff0c;通过每秒播放的帧数&#xff08;帧率&#xff09;来创做&#xff0c;由于GIF动图则以循环播放一系列静态图像帧的方式展现动画效果。由于视频的优势在于流畅的动画、丰富的细节和长时间播放&#xff0c;因此常用于电影、电视节目、…

如何在 Ubuntu / Raspbian 上安装 MariaDB

Raspberry Pi OS&#xff08;原为Raspbian&#xff09;是为树莓派基于Debian开发的操作系统。 从2015年起&#xff0c;树莓派基金会正式将其作为树莓派的官方操作系统。 Raspbian是由Mike Thompson和Peter Green创建的一个独立项目。第一个版本于2012年6月发布&#xff0c;至…

LP-AM243x EtherNet/IP 连接施耐德 M241 EIP主站测试

硬件环境&#xff1a;LP-AM243x 开发板 施耐德 Modicon M241 软件环境&#xff1a; INDUSTRIAL-COMMUNICATIONS-SDK-AM243X MCU-PLUS-SDK-AM243X — MCU SDK for AM243x 调试过程&#xff1a; 首先&#xff0c;让AM243x能够运行 Null Boot&#xff0c; Starting NULL Boo…

Kotlin 尾递归函数

函数式编程中&#xff0c;重要的概念 尾递归。 当一个函数&#xff0c;在函数最后调用 自身&#xff0c;称为 尾递归&#xff0c;是一种特殊的递归函数。 在JVM中&#xff0c;每次方法调用时&#xff0c;都会产生新的栈帧&#xff08;stack frame&#xff09;&#xff0c;消耗栈…

TCP缓存(C++)

系统为每个 socket 创建了发送缓冲区和接收缓冲区&#xff0c;应用程序调用 send()/write()函数发送数据的 时候&#xff0c;内核把数据从应用进程拷贝 socket 的发送缓冲区中&#xff1b;应用程序调用 recv()/read()函数接收数据的时候&#xff0c;内核把数据从 socket 的接收…

C语言实现简单的扫雷游戏

目录 1 -> test.c 2 -> game.c 3 -> game.h 1 -> test.c #define _CRT_SECURE_NO_WARNINGS 1#include "game.h"void menu() {printf("************************************\n");printf("********* 1.play ********\n&quo…

【51单片机】动态数码管

0、前言 参考&#xff1a; 普中51单片机开发攻略–A2.pdf 1、数码管介绍 上一章我们主要是介绍一位数码管的内部结构及控制原理。下面我们再来介 绍下多位数码管及动态显示原理的相关知识。 1.1 多位数码管简介 2、74HC245 和 74HC138 芯片介绍 2.1 74HC245 芯片简介 2.2 7…