Python基础:正则表达式(regular expression)详解

在Python中,正则表达式是一种强大的工具,可用于匹配和操作字符串。什么是正则表达式? 正则表达式是一种模式匹配语言,用于匹配字符串中的特定模式。这些模式可以是字母、数字、字符组合或其他符号。正则表达式通常用于文本处理、网络编程、数据分析等领域。

在 Python 中,正则表达式的实现主要基于 re 模块,该模块提供了一组函数和类,用于处理正则表达式的匹配、搜索和替换。

1. 实现原理:

正则表达式引擎: Python 中的正则表达式引擎使用了正则表达式的编译和匹配两个主要阶段。

编译阶段: 在编译阶段,正则表达式字符串会被解析并转换成一个内部的模式表示。这个模式表示了匹配规则,它包括普通字符、元字符、字符类、分组等。

匹配阶段: 一旦正则表达式被编译,就可以用来匹配字符串。匹配过程是基于模式在字符串中的搜索和比对。引擎会从字符串的起始位置开始,尝试找到与模式匹配的子字符串。

回溯和优化: 在匹配过程中,可能会涉及到回溯的操作,即引擎试图在字符串中不同位置匹配模式。为了提高性能,引擎会使用一些优化策略,避免不必要的回溯。

2. 正则表达式

正则表达式由普通字符和元字符组成。普通字符就是字母、数字、空格等常见字符;元字符则表示特殊含义,例如点号(.)表示任意字符,星号(*)表示零个或多个前面的字符。

常用的元字符及其含义:

.:匹配任意单个字符

\d:匹配数字(等价于 [0-9])

\w:匹配字母、数字、下划线(等价于 [a-zA-Z0-9_])

\s:匹配空格、制表符、换行符等空白字符

^:匹配开头

$:匹配结尾

*:匹配前面的字符零次或多次

+:匹配前面的字符一次或多次

?:匹配前面的字符零次或一次

[]:匹配方括号中任意一个字符

():将其中的内容作为一个组

3.常见示例:

3.1 匹配手机号码

python 复制代码
import re

pattern = r"\d{11}"
string = "My phone number is 12345678901"
match_result = re.search(pattern, string)

if match_result:
    print("Match found:", match_result.group())
else:
    print("Match not found")

3.2 匹配邮政编码

python 复制代码
import re

pattern = r"\b\d{6}\b"
string = "The postal code is 123456"
match_result = re.search(pattern, string)

if match_result:
    print("Match found:", match_result.group())
else:
    print("Match not found")

3.3 提取HTML标签中的内容

python 复制代码
import re

pattern = r"<.*?>"
html_string = "<p>This is a <b>bold</b> statement.</p>"
match_result = re.findall(pattern, html_string)

print("Matches found:", match_result)

3.4 提取HTML中的链接(href属性)

python 复制代码
import re

pattern = r'href="(.*?)"'
html_code = '<a href="https://www.example.com">Visit our website</a>'
match_result = re.search(pattern, html_code)

if match_result:
    print("Match found:", match_result.group(1))
else:
    print("Match not found")

3.5 匹配IP地址

python 复制代码
import re

pattern = r"\b(?:\d{1,3}\.){3}\d{1,3}\b"
string = "Server's IP address is 192.168.1.1"
match_result = re.search(pattern, string)

if match_result:
    print("Match found:", match_result.group())
else:
    print("Match not found")

3.6 匹配URL

python 复制代码
import re

pattern = r"https?://\S+"
text = "Visit our website at https://www.example.com"
match_result = re.search(pattern, text)

if match_result:
    print("Match found:", match_result.group())
else:
    print("Match not found")

3.7 匹配日期(yyyy-mm-dd)

python 复制代码
import re

pattern = r"\b\d{4}-\d{2}-\d{2}\b"
text = "Event date: 2022-12-31"
match_result = re.search(pattern, text)

if match_result:
    print("Match found:", match_result.group())
else:
    print("Match not found")

3.8 匹配邮箱地址

python 复制代码
import re

pattern = r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b"
text = "Contact us at info@example.com or support@company.net"
match_result = re.findall(pattern, text)

print("Matches found:", match_result)

3.9 匹配全名中的姓氏

python 复制代码
import re

pattern = r"\b[A-Z][a-z]+\b"
full_name = "John Doe"
match_result = re.findall(pattern, full_name)

print("Matches found:", match_result)

3.10 匹配中文名字

python 复制代码
import re

pattern = r'^[\u4e00-\u9fa5]{1,5}$'
name = "王小明"

match_result = re.match(pattern, name)

if match_result:
    print("Match found:", match_result.group())
else:
    print("Match not found")

3.11 匹配字符串中的所有单词

python 复制代码
import re

pattern = r"\b\w+\b"
text = "This is a simple example."
match_result = re.findall(pattern, text)

print("Matches found:", match_result)
相关推荐
waterHBO2 小时前
python 爬虫 selenium 笔记
爬虫·python·selenium
编程零零七3 小时前
Python数据分析工具(三):pymssql的用法
开发语言·前端·数据库·python·oracle·数据分析·pymssql
AIAdvocate5 小时前
Pandas_数据结构详解
数据结构·python·pandas
小言从不摸鱼5 小时前
【AI大模型】ChatGPT模型原理介绍(下)
人工智能·python·深度学习·机器学习·自然语言处理·chatgpt
FreakStudio7 小时前
全网最适合入门的面向对象编程教程:50 Python函数方法与接口-接口和抽象基类
python·嵌入式·面向对象·电子diy
redcocal8 小时前
地平线秋招
python·嵌入式硬件·算法·fpga开发·求职招聘
artificiali8 小时前
Anaconda配置pytorch的基本操作
人工智能·pytorch·python
RaidenQ8 小时前
2024.9.13 Python与图像处理新国大EE5731课程大作业,索贝尔算子计算边缘,高斯核模糊边缘,Haar小波计算边缘
图像处理·python·算法·课程设计
花生了什么树~.9 小时前
python基础知识(六)--字典遍历、公共运算符、公共方法、函数、变量分类、参数分类、拆包、引用
开发语言·python
Trouvaille ~9 小时前
【Python篇】深度探索NumPy(下篇):从科学计算到机器学习的高效实战技巧
图像处理·python·机器学习·numpy·信号处理·时间序列分析·科学计算