Python正则表达式Regular Expression初探

news2025/1/14 1:07:10

目录

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.coloradmin.cn/o/1401283.html

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

相关文章

Java Web现代化开发:Spring Boot + Mybatis + Redis二级缓存

Java Web现代化开发&#xff1a;Spring Boot Mybatis Redis二级缓存 背景 Spring-Boot因其提供了各种开箱即用的插件&#xff0c;使得它成为了当今最为主流的Java Web开发框架之一。Mybatis是一个十分轻量好用的ORM框架。Redis是当今十分主流的分布式key-value型数据库&…

【云上探索实验室】使用 Amazon Bedrock 体验构建Stable Diffusion-文本生成图像生成式 AI 应用

生成式人工智能&#xff08;AI&#xff09;正以惊人的速度蓬勃发展&#xff0c;不断推动着科技创新的边界。在前不久的re:Invent 2023大会上&#xff0c;Selipsky为我们重点介绍了全托管式生成式 AI 服务 Amazon Bedrock&#xff0c;并表示Amazon Bedrock 极大地降低了客户从基…

༺༽༾ཊ—设计-简单-02-工厂-模式—ཏ༿༼༻

名称&#xff1a;简单工厂 类型&#xff1a;创建型 目的&#xff1a;用 工厂方法 代替 new操作 创建实例 的方式 缺点&#xff1a;不易扩展 首先我们创建一个接口 定义两个私有方法 并在两个新建类 下继承 实现接口 【注意】&#xff1a;一旦继承接口&#xff0c;必须实现…

计组原理:系统概论与基本组成

系统概论与基本组成 系统概论硬件软件 计算机系统的层次结构系统复杂性的管理方法1&#xff1a;抽象 计算机的基本组成冯诺依曼计算机系统复杂性的管理方法 2&#xff1a;&#xff08;3’Y&#xff09; 计算机的工作步骤上机前的准备&#xff1a;计算机的解题过程存储器的基本组…

结构体内存对齐(面试重点)

结构体内存对齐 1. 结构体类型的声明1.1 结构体的概念1.1.1 结构的声明1.1.2 结构体变量的创建和初始化 1.2 结构的特殊声明1.3 结构的自引用 2. 结构体内存对齐2.1 对齐规则2.1.1 练习1:2.1.2 练习2:2.1.3 练习3:2.1.4 练习4: 2.2 offsetof宏的使用2.3 为什么存在内存对齐?2.…

蓝桥杯省赛无忧 编程7

为了解决这个问题&#xff0c;我们可以编写一个函数来计算从编号为1的石头到达编号为n的石头所需的最少步数。问题的关键是理解每一步的移动规则&#xff1a;从当前石头编号n移动到编号为nx的石头上&#xff0c;其中x是n的各位数字之和。因此&#xff0c;我们需要一个辅助函数来…

docker 部署 sentinel

docker 部署 sentinel 环境安装 拉取镜像 目前稳定的版本是1.8.0 docker pull bladex/sentinel-dashboard:1.8.0启动服务 docker run --name sentinel -p 8858:8858 -td bladex/sentinel-dashboard:1.8.0登录 登录的时候账号和密码都是sentinel

[安全警报] Npm木马利用“Oscompatible“包悄然安装AnyDesk

最近&#xff0c;一个名为OsCompatible的恶意包被上传到npm 。该包被发现包含一个针对 Windows 的远程访问木马。 这个名为OsCompatible的软件包于2024年1月9日发布&#xff0c;在被撤下之前共吸引了380次下载。 据了解&#xff0c;OsCompatible包含“几个奇怪的二进制文件”…

解决 pnpm : 无法加载文件 C:\Program Files\nodejs\pnpm.ps1,因为在此系统上禁止运行脚本。

执行下面命令进行安装pnpm安装后 npm install -g pnpm 然后执行pnpm 报错 解决办法&#xff1a; 以管理员身份运行 Windows PowerShell &#xff0c; 在命令行输入以下命令后按回车&#xff0c; set-ExecutionPolicy RemoteSigned 再输入Y 回车即可。 再回到控制台输入p…

Elasticsearch Index Shard Allocation 索引分片分配策略

Elasticsearch 索引分片的分配策略说明 在上一篇《索引生命周期管理ILM看完不懂你锤我 》&#xff08;https://mp.weixin.qq.com/s/ajhFp-xBU1dJm8a1dDdRQQ&#xff09;中&#xff0c;我们已经学会了索引级别的分片分配过滤属性&#xff0c;也就是在配置文件中指定当前节点的属…

srm-50——攻防世界

可以知道这道题是二类题型&#xff0c;你完成某个事情给你flag 我们输入正确的东西&#xff0c;给“flag” 运行一下可以知道这些关键词 直接关键词在字符串里面 找到运行得到的东西 INT_PTR __stdcall DialogFunc(HWND hDlg, UINT a2, WPARAM a3, LPARAM a4) {HMODULE Mo…

Vue 组件通信方式

✨ 专栏介绍 在当今Web开发领域中&#xff0c;构建交互性强、可复用且易于维护的用户界面是至关重要的。而Vue.js作为一款现代化且流行的JavaScript框架&#xff0c;正是为了满足这些需求而诞生。它采用了MVVM架构模式&#xff0c;并通过数据驱动和组件化的方式&#xff0c;使…

天津想转行学python培训班靠谱吗?

现在的职业如此繁多&#xff0c;很多人把高薪当成衡量工作好坏的重要标准&#xff0c;因此IT行业以超出其他行业几倍薪资水平成为不错的选择&#xff0c;而Python又以其简单易学好上手成为大家所青睐的学习目标。 Python发展前景如何 Python语言就业发展方向广泛&#xff1a;…

SpringSecurity+OAuth2.0 搭建认证中心和资源服务中心

目录 1. OAuth2.0 简介 2. 代码搭建 2.1 认证中心&#xff08;8080端口&#xff09; 2.2 资源服务中心&#xff08;8081端口&#xff09; 3. 测试结果 1. OAuth2.0 简介 OAuth 2.0&#xff08;开放授权 2.0&#xff09;是一个开放标准&#xff0c;用于授权第三方应用程序…

java垃圾回收GC过程

GC&#xff08;Gabage Collection&#xff09; 用于回收堆中的垃圾数据 清理方法 1.标记-清理 对数据标记&#xff0c;然后清理 缺点&#xff1a;容易产生内存碎片 2.标记-整理 对标记后的数据清理&#xff0c;剩下数据前移 缺点&#xff1a;每次清理后数据都要迁移&#xff0…

代码随想录二刷 | 回溯 | 组合优化

代码随想录二刷 &#xff5c; 回溯 &#xff5c; 组合优化 剪枝优化 剪枝优化 在遍历的过程中有如下代码&#xff1a; for (int i startIndex; i < n; i) {path.pop_back();backtracking(n, k, i 1);path.pop_back(); }n 4&#xff0c;k 4的话&#xff0c;那么第一层f…

qemu使用

百度qemu bios 问题 坑爹的玩意&#xff0c;编译qemu 还需要python3.5以上 解决方法&#xff1a; CentOS7安装Python3.8-CSDN博客 https://www.cnblogs.com/Oliver.net/p/7211967.html 编译python3.8还由于openssl过低 参考 QEMU启动x86-Linux内核_qemu-system-x86-…

SaaS多租户篇

文章目录 1. 多租户是什么2. 技术组件2.1 如何实现多租户的DB封装2.2 如何实现多租户的redis封装2.3 如何实现多租户的Web和Security封装2.4 如何实现多租户的Job封装2.5 如何实现多租户的 MQ 与 Async 封装&#xff1f;2.6 如何实现多租户的 AOP 与 Util 封装&#xff1f; 3.业…

【Qt之模型视图】5. Qt库提供的视图便捷类

1. 前言 Qt提供了一些便捷的视图类&#xff0c;如QListWidget提供项目列表&#xff0c;QTreeWidget显示多级树结构&#xff0c;QTableWidget提供单元格项的表格。每个类都继承了QAbstractItemView类的行为&#xff0c;QAbstractItemView类实现了项目选择和标题管理的通用行为。…

《WebKit 技术内幕》之五(1): HTML解释器和DOM 模型

第五章 HTML 解释器和 DOM 模型 1.DOM 模型 1.1 DOM标准 DOM &#xff08;Document Object Model&#xff09;的全称是文档对象模型&#xff0c;它可以以一种独立于平台和语言的方式访问和修改一个文档的内容和结构。这里的文档可以是 HTML 文档、XML 文档或者 XHTML 文档。D…