目录
RegEx 模块
Python 中的 RegEx
RegEx 函数
元字符
特殊序列
集合(Set)
findall() 函数
search() 函数
split() 函数
sub() 函数
Match 对象
首页 后端开发 Python教程 Python的RegEx正则表达式怎么使用

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

May 19, 2023 pm 08:49 PM
python regex

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 对象。

以上是Python的RegEx正则表达式怎么使用的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

在PHP和Python之间进行选择:指南 在PHP和Python之间进行选择:指南 Apr 18, 2025 am 12:24 AM

PHP适合网页开发和快速原型开发,Python适用于数据科学和机器学习。1.PHP用于动态网页开发,语法简单,适合快速开发。2.Python语法简洁,适用于多领域,库生态系统强大。

PHP和Python:解释了不同的范例 PHP和Python:解释了不同的范例 Apr 18, 2025 am 12:26 AM

PHP主要是过程式编程,但也支持面向对象编程(OOP);Python支持多种范式,包括OOP、函数式和过程式编程。PHP适合web开发,Python适用于多种应用,如数据分析和机器学习。

vs code 可以在 Windows 8 中运行吗 vs code 可以在 Windows 8 中运行吗 Apr 15, 2025 pm 07:24 PM

VS Code可以在Windows 8上运行,但体验可能不佳。首先确保系统已更新到最新补丁,然后下载与系统架构匹配的VS Code安装包,按照提示安装。安装后,注意某些扩展程序可能与Windows 8不兼容,需要寻找替代扩展或在虚拟机中使用更新的Windows系统。安装必要的扩展,检查是否正常工作。尽管VS Code在Windows 8上可行,但建议升级到更新的Windows系统以获得更好的开发体验和安全保障。

vscode 扩展是否是恶意的 vscode 扩展是否是恶意的 Apr 15, 2025 pm 07:57 PM

VS Code 扩展存在恶意风险,例如隐藏恶意代码、利用漏洞、伪装成合法扩展。识别恶意扩展的方法包括:检查发布者、阅读评论、检查代码、谨慎安装。安全措施还包括:安全意识、良好习惯、定期更新和杀毒软件。

vscode怎么在终端运行程序 vscode怎么在终端运行程序 Apr 15, 2025 pm 06:42 PM

在 VS Code 中,可以通过以下步骤在终端运行程序:准备代码和打开集成终端确保代码目录与终端工作目录一致根据编程语言选择运行命令(如 Python 的 python your_file_name.py)检查是否成功运行并解决错误利用调试器提升调试效率

visual studio code 可以用于 python 吗 visual studio code 可以用于 python 吗 Apr 15, 2025 pm 08:18 PM

VS Code 可用于编写 Python,并提供许多功能,使其成为开发 Python 应用程序的理想工具。它允许用户:安装 Python 扩展,以获得代码补全、语法高亮和调试等功能。使用调试器逐步跟踪代码,查找和修复错误。集成 Git,进行版本控制。使用代码格式化工具,保持代码一致性。使用 Linting 工具,提前发现潜在问题。

vscode 可以用于 mac 吗 vscode 可以用于 mac 吗 Apr 15, 2025 pm 07:36 PM

VS Code 可以在 Mac 上使用。它具有强大的扩展功能、Git 集成、终端和调试器,同时还提供了丰富的设置选项。但是,对于特别大型项目或专业性较强的开发,VS Code 可能会有性能或功能限制。

vscode 可以运行 ipynb 吗 vscode 可以运行 ipynb 吗 Apr 15, 2025 pm 07:30 PM

VS Code 运行 Jupyter Notebook 的关键是要确保 Python 环境正确配置,理解代码执行顺序与单元格顺序一致,并注意可能影响性能的大型文件或外部库。VS Code 提供的代码补全和调试功能可以大大提高编码效率和减少错误。

See all articles