当前位置:

首页 > 编程开发 > Python的RegEx正则表达式怎么使用

Python的RegEx正则表达式怎么使用

RegEx或正则表达式是形成搜索模式的字符序列。RegEx可用于检查字符串是否包含指定的搜索模式。RegEx模块Python提供名为re的内置包,可用于处理正则表达式。导入re模块:importrePython中的RegEx导入re模块后,就可以开始使用正则表达式了:实例检索字符串以查看它是否以“China”开头并以“country”结尾:importretxt="Chinaisagreatcountry"x=re.search("^China.*country$",txt)运行实例importretxt

本文目录

    RegEx 或正则表达式是形成搜索模式的字符序列。

    RegEx 可用于检查字符串是否包含指定的搜索模式。

    RegEx 模块

    Python 提供名为 re 的内置包,可用于处理正则表达式。

    导入 re 模块:

    import re

    Python 中的 RegEx

    导入 re 模块后,就可以开始使用正则表达式了:

    实例

    检索字符串以查看它是否以 “China” 开头并以 “country” 结尾:

    import re
    
    txt = "China is a great country"
    x = re.search("^China.*country$", txt)

    运行实例

    import re
    
    txt = "China is a great country"
    x = re.search("^China.*country$", txt)
    
    if (x):
      print("YES! We have a match!")
    else:
      print("No match")

    Python的RegEx正则表达式怎么使用

    RegEx 函数

    re 模块提供了一组函数,允许我们检索字符串以进行匹配:

    Python的RegEx正则表达式怎么使用

    元字符

    元字符是具有特殊含义的字符

    字符:[] 描述:一组字符 示例:“[a-m]”

    import re
    
    str = "The rain in Spain"
    
    #Find all lower case characters alphabetically between "a" and "m":
    
    x = re.findall("[a-m]", str)
    print(x)

    运行示例

    Python的RegEx正则表达式怎么使用

    字符: 描述:示意特殊序列(也可用于转义特殊字符) 示例:“\d”

    import re
    
    str = "That will be 59 dollars"
    
    #Find all digit characters:
    
    x = re.findall("\d", str)
    print(x)

    运行示例

    Python的RegEx正则表达式怎么使用

    字符:. 描述:任何字符(换行符除外) 示例: “he…o”

    import re
    
    str = "hello world"
    
    #Search for a sequence that starts with "he", followed by two (any) characters, and an "o":
    
    x = re.findall("he..o", str)
    print(x)

    运行示例

    Python的RegEx正则表达式怎么使用

    字符:^ 描述:起始于 示例: “^hello”

    import re
    
    str = "hello world"
    
    #Check if the string starts with 'hello':
    
    x = re.findall("^hello", str)
    if (x):
      print("Yes, the string starts with 'hello'")
    else:
      print("No match")

    运行示例

    Python的RegEx正则表达式怎么使用

    字符:$ 描述:结束于 示例:“world$”

    import re
    
    str = "hello world"
    
    #Check if the string ends with 'world':
    
    x = re.findall("world$", str)
    if (x):
      print("Yes, the string ends with 'world'")
    else:
      print("No match")

    运行示例

    Python的RegEx正则表达式怎么使用

    字符:* 描述:零次或多次出现 示例:“aix*”

    import re
    
    str = "The rain in Spain falls mainly in the plain!"
    
    #Check if the string contains "ai" followed by 0 or more "x" characters:
    
    x = re.findall("aix*", str)
    
    print(x)
    
    if (x):
      print("Yes, there is at least one match!")
    else:
      print("No match")

    运行示例

    Python的RegEx正则表达式怎么使用

    字符:+ 描述:一次或多次出现 示例: “aix+”

    import re
    
    str = "The rain in Spain falls mainly in the plain!"
    
    #Check if the string contains "ai" followed by 1 or more "x" characters:
    
    x = re.findall("aix+", str)
    
    print(x)
    
    if (x):
      print("Yes, there is at least one match!")
    else:
      print("No match")

    运行示例

    Python的RegEx正则表达式怎么使用

    字符:{} 描述: 确切地指定的出现次数 示例:“al{2}”

    import re
    
    str = "The rain in Spain falls mainly in the plain!"
    
    #Check if the string contains "a" followed by exactly two "l" characters:
    
    x = re.findall("al{2}", str)
    
    print(x)
    
    if (x):
      print("Yes, there is at least one match!")
    else:
      print("No match")

    运行示例

    Python的RegEx正则表达式怎么使用

    字符:| 描述:两者任一 示例:“falls|stays”

    import re
    
    str = "The rain in Spain falls mainly in the plain!"
    
    #Check if the string contains either "falls" or "stays":
    
    x = re.findall("falls|stays", str)
    
    print(x)
    
    if (x):
      print("Yes, there is at least one match!")
    else:
      print("No match")

    运行示例

    Python的RegEx正则表达式怎么使用

    字符:() 描述:捕获和分组

    特殊序列

    特殊序列指的是 \ 后跟下表中的某个字符,拥有特殊含义。

    字符:\A 描述:如果指定的字符位于字符串的开头,则返回匹配项 示例:“\AThe”

    import re
    
    str = "The rain in Spain"
    
    #Check if the string starts with "The":
    
    x = re.findall("\AThe", str)
    
    print(x)
    
    if (x):
      print("Yes, there is a match!")
    else:
      print("No match")

    运行示例

    Python的RegEx正则表达式怎么使用

    字符:\b

    描述:返回指定字符位于单词的开头或末尾的匹配项

    示例:r"\bain"

    import re
    
    str = "The rain in Spain"
    
    #Check if "ain" is present at the beginning of a WORD:
    
    x = re.findall(r"\bain", str)
    
    print(x)
    
    if (x):
      print("Yes, there is at least one match!")
    else:
      print("No match")

    运行示例

    Python的RegEx正则表达式怎么使用

    示例:r"ain\b"

    import re
    
    str = "The rain in Spain"
    
    #Check if "ain" is present at the end of a WORD:
    
    x = re.findall(r"ain\b", str)
    
    print(x)
    
    if (x):
      print("Yes, there is at least one match!")
    else:
      print("No match")

    运行示例

    Python的RegEx正则表达式怎么使用

    字符:\B

    描述:返回指定字符存在的匹配项,但不在单词的开头(或结尾处)

    示例:r"\Bain"

    import re
    
    str = "The rain in Spain"
    
    #Check if "ain" is present, but NOT at the beginning of a word:
    
    x = re.findall(r"\Bain", str)
    
    print(x)
    
    if (x):
      print("Yes, there is at least one match!")
    else:
      print("No match")

    运行示例

    Python的RegEx正则表达式怎么使用

    示例:r"ain\B"

    import re
    
    str = "The rain in Spain"
    
    #Check if "ain" is present, but NOT at the end of a word:
    
    x = re.findall(r"ain\B", str)
    
    print(x)
    
    if (x):
      print("Yes, there is at least one match!")
    else:
      print("No match")

    运行示例

    Python的RegEx正则表达式怎么使用

    字符:\d

    描述:返回字符串包含数字的匹配项(数字 0-9)

    示例:“\d”

    import re
    
    str = "The rain in Spain"
    
    #Check if the string contains any digits (numbers from 0-9):
    
    x = re.findall("\d", str)
    
    print(x)
    
    if (x):
      print("Yes, there is at least one match!")
    else:
      print("No match")

    运行示例

    Python的RegEx正则表达式怎么使用

    字符:\D

    描述:返回字符串不包含数字的匹配项

    示例:“\D”

    import re
    
    str = "The rain in Spain"
    
    #Return a match at every no-digit character:
    
    x = re.findall("\D", str)
    
    print(x)
    
    if (x):
      print("Yes, there is at least one match!")
    else:
      print("No match")

    运行示例

    Python的RegEx正则表达式怎么使用

    字符:\s

    描述:返回字符串包含空白字符的匹配项

    示例:“\s”

    import re
    
    str = "The rain in Spain"
    
    #Return a match at every white-space character:
    
    x = re.findall("\s", str)
    
    print(x)
    
    if (x):
      print("Yes, there is at least one match!")
    else:
      print("No match")

    运行示例

    Python的RegEx正则表达式怎么使用

    字符:\S

    描述:返回字符串不包含空白字符的匹配项

    示例:“\S”

    import re
    
    str = "The rain in Spain"
    
    #Return a match at every NON white-space character:
    
    x = re.findall("\S", str)
    
    print(x)
    
    if (x):
      print("Yes, there is at least one match!")
    else:
      print("No match")

    运行示例

    Python的RegEx正则表达式怎么使用

    字符:\w

    描述: 返回一个匹配项,其中字符串包含任何单词字符 (从 a 到 Z 的字符,从 0 到 9 的数字和下划线 _ 字符)

    示例:“\w”

    import re
    
    str = "The rain in Spain"
    
    #Return a match at every word character (characters from a to Z, digits from 0-9, and the underscore _ character):
    
    x = re.findall("\w", str)
    
    print(x)
    
    if (x):
      print("Yes, there is at least one match!")
    else:
      print("No match")

    运行示例

    Python的RegEx正则表达式怎么使用

    字符:\W

    描述:返回一个匹配项,其中字符串不包含任何单词字符

    示例:“\W”

    import re
    
    str = "The rain in Spain"
    
    #Return a match at every NON word character (characters NOT between a and Z. Like "!", "?" white-space etc.):
    
    x = re.findall("\W", str)
    
    print(x)
    
    if (x):
      print("Yes, there is at least one match!")
    else:
      print("No match")

    运行示例

    Python的RegEx正则表达式怎么使用

    字符:\Z

    描述:如果指定的字符位于字符串的末尾,则返回匹配项 。

    示例:“Spain\Z”

    import re
    
    str = "The rain in Spain"
    
    #Check if the string ends with "Spain":
    
    x = re.findall("Spain\Z", str)
    
    print(x)
    
    if (x):
      print("Yes, there is a match!")
    else:
      print("No match")

    运行示例

    Python的RegEx正则表达式怎么使用

    集合(Set)

    集合(Set)是一对方括号 [] 内的一组字符,具有特殊含义。

    字符:[arn]

    描述:返回一个匹配项,其中存在指定字符(a,r 或 n)之一

    示例

    import re
    
    str = "The rain in Spain"
    
    #Check if the string has any a, r, or n characters:
    
    x = re.findall("[arn]", str)
    
    print(x)
    
    if (x):
      print("Yes, there is at least one match!")
    else:
      print("No match")

    运行示例

    Python的RegEx正则表达式怎么使用

    字符:[a-n]

    描述:返回字母顺序 a 和 n 之间的任意小写字符匹配项

    示例

    import re
    
    str = "The rain in Spain"
    
    #Check if the string has any characters between a and n:
    
    x = re.findall("[a-n]", str)
    
    print(x)
    
    if (x):
      print("Yes, there is at least one match!")
    else:
      print("No match")

    运行示例

    Python的RegEx正则表达式怎么使用

    字符:[^arn]

    描述:返回除 a、r 和 n 之外的任意字符的匹配项

    示例

    import re
    
    str = "The rain in Spain"
    
    #Check if the string has other characters than a, r, or n:
    
    x = re.findall("[^arn]", str)
    
    print(x)
    
    if (x):
      print("Yes, there is at least one match!")
    else:
      print("No match")

    运行示例

    Python的RegEx正则表达式怎么使用

    字符:[0123]

    描述:返回存在任何指定数字(0、1、2 或 3)的匹配项

    示例

    import re
    
    str = "The rain in Spain"
    
    #Check if the string has any 0, 1, 2, or 3 digits:
    
    x = re.findall("[0123]", str)
    
    print(x)
    
    if (x):
      print("Yes, there is at least one match!")
    else:
      print("No match")

    运行示例

    Python的RegEx正则表达式怎么使用

    字符:[0-9]

    描述:返回 0 与 9 之间任意数字的匹配

    示例

    import re
    
    str = "8 times before 11:45 AM"
    
    #Check if the string has any digits:
    
    x = re.findall("[0-9]", str)
    
    print(x)
    
    if (x):
      print("Yes, there is at least one match!")
    else:
      print("No match")

    运行示例

    Python的RegEx正则表达式怎么使用

    字符:[0-5][0-9]

    描述:返回介于 0 到 9 之间的任何数字的匹配项

    示例

    import re
    
    str = "8 times before 11:45 AM"
    
    #Check if the string has any two-digit numbers, from 00 to 59:
    
    x = re.findall("[0-5][0-9]", str)
    
    print(x)
    
    if (x):
      print("Yes, there is at least one match!")
    else:
      print("No match")

    运行示例

    Python的RegEx正则表达式怎么使用

    字符:[a-zA-Z]

    描述:返回字母顺序 a 和 z 之间的任何字符的匹配,小写或大写

    示例

    import re
    
    str = "8 times before 11:45 AM"
    
    #Check if the string has any characters from a to z lower case, and A to Z upper case:
    
    x = re.findall("[a-zA-Z]", str)
    
    print(x)
    
    if (x):
      print("Yes, there is at least one match!")
    else:
      print("No match")

    运行示例

    Python的RegEx正则表达式怎么使用

    字符:[+]

    描述:在集合中,+、*、.、|、()、$、{} 没有特殊含义,因此 [+] 表示:返回字符串中任何 + 字符的匹配项。

    示例

    import re
    
    str = "8 times before 11:45 AM"
    
    #Check if the string has any + characters:
    
    x = re.findall("[+]", str)
    
    print(x)
    
    if (x):
      print("Yes, there is at least one match!")
    else:
      print("No match")

    运行示例

    Python的RegEx正则表达式怎么使用

    findall() 函数

    findall() 函数返回包含所有匹配项的列表。

    实例

    打印所有匹配的列表

    import re
    
    str = "China is a great country"
    x = re.findall("a", str)
    print(x)

    运行实例

    Python的RegEx正则表达式怎么使用

    这个列表以被找到的顺序包含匹配项。

    如果未找到匹配项,则返回空列表。

    实例

    如果未找到匹配,则返回空列表:

    import re
    
    str = "China is a great country"
    x = re.findall("USA", str)
    print(x)

    运行实例

    Python的RegEx正则表达式怎么使用

    search() 函数

    search() 函数搜索字符串中的匹配项,如果存在匹配则返回 Match 对象。

    如果有多个匹配,则仅返回首个匹配项。

    实例

    在字符串中搜索第一个空白字符

    import re
    
    str = "China is a great country"
    x = re.search("\s", str)
    
    print("The first white-space character is located in position:", x.start())

    运行实例

    Python的RegEx正则表达式怎么使用

    如果未找到匹配,则返回值 None:

    实例

    进行不返回匹配的检索

    import re
    
    str = "China is a great country"
    x = re.search("USA", str)
    print(x)

    运行实例

    Python的RegEx正则表达式怎么使用

    split() 函数

    split() 函数返回一个列表,其中字符串在每次匹配时被拆分。

    实例

    在每个空白字符处进行拆分

    import re
    
    str = "China is a great country"
    x = re.split("\s", str)
    print(x)

    运行实例

    Python的RegEx正则表达式怎么使用

    可以通过指定 maxsplit 参数来控制出现次数:

    实例

    仅在首次出现时拆分字符串:

    import re
    
    str = "China is a great country"
    x = re.split("\s", str, 1)
    print(x)

    运行实例

    Python的RegEx正则表达式怎么使用

    sub() 函数

    sub() 函数把匹配替换为您选择的文本

    实例

    用数字 9 替换每个空白字符

    import re
    
    str = "China is a great country"
    x = re.sub("\s", "9", str)
    print(x)

    运行实例

    Python的RegEx正则表达式怎么使用

    可以通过指定 count 参数来控制替换次数:

    实例

    替换前两次出现

    import re
    
    str = "China is a great country"
    x = re.sub("\s", "9", str, 2)
    print(x)

    运行实例

    Python的RegEx正则表达式怎么使用

    Match 对象

    Match 对象是包含有关搜索和结果信息的对象。

    注释:如果没有匹配,则返回值 None,而不是 Match 对象。

    实例

    执行会返回 Match 对象的搜索:

    import re
    
    str = "China is a great country"
    x = re.search("a", str)
    print(x) # 将打印一个对象

    运行实例

    Python的RegEx正则表达式怎么使用

    Match 对象提供了用于取回有关搜索及结果信息的属性和方法:

    • span() 返回的元组包含了匹配的开始和结束位置

    • .string 返回传入函数的字符串

    • group() 返回匹配的字符串部分

    实例

    打印首个匹配出现的位置(开始和结束位置)。

    正则表达式查找以大写 “C” 开头的任何单词:

    import re
    
    str = "China is a great country"
    x = re.search(r"\bC\w+", str)
    print(x.span())

    运行实例

    Python的RegEx正则表达式怎么使用

    实例

    打印传入函数的字符串

    import re
    
    str = "China is a great country"
    x = re.search(r"\bC\w+", str)
    print(x.string)

    运行实例

    Python的RegEx正则表达式怎么使用

    实例

    打印匹配的字符串部分

    正则表达式查找以大写 “C” 开头的任何单词:

    import re
    
    str = "China is a great country"
    x = re.search(r"\bC\w+", str)
    print(x.group())

    运行实例

    Python的RegEx正则表达式怎么使用

    注释:如果没有匹配项,则返回值 None,而不是 Match 对象。

    本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系bd@zhengruan.com
    作者最新文章
    编程开发 Python
    相关文章 更多
    python删除一个列表里的重复元素的方法与代码示例
    python删除一个列表里的重复元素的方法与代码示例

    学习如何使用Python高效删除列表中的重复元素。本文提供5种常见方法的代码示例,涵盖保持顺序与不保持顺序的场景,适合初学者和进阶开发者参考。

    Python写接口的步骤及完整代码示例
    Python写接口的步骤及完整代码示例

    详细讲解使用Python编写Web接口的核心步骤与完整代码示例,涵盖环境准备、路由定义、数据校验、服务启动及调试测试方法。

    codex怎么读取word文档及docx文件操作教程
    codex怎么读取word文档及docx文件操作教程

    介绍如何利用编程工具读取和解析Word文档(docx格式),涵盖基础文本提取代码示例、结构化数据处理逻辑,以及处理复杂排版时的技术局限与替代方案。

    怎么在Python中调用C语言代码提升性能
    怎么在Python中调用C语言代码提升性能

    详细讲解在Python中调用C语言代码提升性能的完整实践指南,包含原理分析、编译步骤、ctypes与CFFI具体实现、性能对比及常见陷阱。

    Python与C语言的性能差异及底层原理
    Python与C语言的性能差异及底层原理

    深入解析Python与C语言在执行效率上的数量级差异,从编译机制、变量内存布局、动态类型推断到GIL锁,系统阐明底层核心原理。

    Python和C语言哪个更适合编程入门
    Python和C语言哪个更适合编程入门

    客观对比Python与C语言在心智负担、底层机制与学习反馈上的核心差异,提供清晰有据的选择标准与切实的入门学习路径。

    selenium上传文件教程本地文件路径设置方法
    selenium上传文件教程本地文件路径设置方法

    深入解析Selenium处理文件上传的技术细节,涵盖标准HTML控件的路径直接注入法与非标准控件的系统级模拟方案,提供Windows与Linux环境下的路径设置最佳实践及常见异常排查。

    大数据开发语言选型:Java对比Scala与Python的优缺点及适用场景
    大数据开发语言选型:Java对比Scala与Python的优缺点及适用场景

    针对大数据工程场景,系统对比Java、Scala与Python在执行性能、生态结合、开发效率和维护成本上的核心差异,给出清晰的架构选型依据与落地方案。

    langgraph python guide中文入门教程详解
    langgraph python guide中文入门教程详解

    本篇LangGraph Python中文入门教程详解,系统梳理StateGraph状态机定义、节点编写、边与条件路由、检查点持久化(MemorySaver)等核心机制,提供从环境安装到完整循环智能体构建的代码示例与实操指导。

    Windows 安装 Python:从官方入口到虚拟环境的可复现实践
    Windows 安装 Python:从官方入口到虚拟环境的可复现实践

    面向后端开发者,基于 Python 官方文档说明如何在 Windows 上安装 Python、创建 venv 虚拟环境及使用 pip 管理依赖。包含可复制命令、验证方法及工具选择边界,避免常见配置误区。

    查看更多
    精品专题 更多
    装机必备
    装机必备

    正软商城装机必备专区,精选办公、浏览器、安全防护、影音播放、压缩解压、设计创作和系统工具等电脑常用正版软件,帮助用户快速完成新电脑软件配置。

    Windows
    Windows

    正软商城Windows软件专区,汇集适用于Windows电脑的办公、设计、安全防护、影音播放、开发工具和系统优化软件,提供软件介绍、系统要求、正版授权及购买下载服务。

    PDF教程
    PDF教程

    正软商城PDF教程频道提供PDF编辑、转换、合并、拆分、压缩及格式处理方法,同时介绍常用PDF软件和工具的使用技巧。

    Mac软件 更多
    讯飞智作 网页版
    讯飞智作 网页版
    Windows/ macOS/ Linux

    讯飞智作是一款基于语音合成技术、虚拟人驱动技术与数字人形象声音构建能力的 AI 数字人音视频创作平台。

    火山引擎 网页版
    火山引擎 网页版
    Windows/ macOS/ Linux

    火山引擎是字节跳动旗下企业级云与AI服务平台。聚焦大模型核心能力,依托字节自研豆包多模态大模型,凭借火山方舟一站式平台,提供模型精调、推理部署、智能应用搭建等全链路服务,结合高性能AI算力,助力各行业快速落地大模型数字化与智能化应用。

    Aperty macOS版
    Aperty macOS版
    macOS

    Aperty 是 Skylum 推出的 AI 人像修图软件,支持自然肤质修饰、瑕疵处理、面部与身体调整、预设及批量同步。

    WINDOWS 更多
    讯飞智作 网页版
    讯飞智作 网页版
    Windows/ macOS/ Linux

    讯飞智作是一款基于语音合成技术、虚拟人驱动技术与数字人形象声音构建能力的 AI 数字人音视频创作平台。

    火山引擎 网页版
    火山引擎 网页版
    Windows/ macOS/ Linux

    火山引擎是字节跳动旗下企业级云与AI服务平台。聚焦大模型核心能力,依托字节自研豆包多模态大模型,凭借火山方舟一站式平台,提供模型精调、推理部署、智能应用搭建等全链路服务,结合高性能AI算力,助力各行业快速落地大模型数字化与智能化应用。

    PixTV 网页版
    PixTV 网页版
    Windows

    PixTV 是一款在浏览器中使用的 AI 视觉内容创作平台,提供图片、视频、音频、文字生成、AI 分镜、局部重绘、提示词反推和无限画布等工具,适合短剧、漫剧、广告及社交媒体内容制作。