【python学习】基础篇-常用模块-re模块:正则表达式高效操作字符串

在Python中,正则表达式主要通过re模块来实现。以下是一些常用的正则表达式用法:

匹配值:

python 复制代码
pattern = r'\d+'  # 匹配一个或多个数字
pattern = r'\b\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\b' #匹配日期格式
pattern = r'hello'  # 匹配字符串"hello"
  • \d 表示匹配一个数字字符,等价于 [0-9];
  • +表示匹配前面的子表达式一次或多次
  • \d{4}表示匹配四位数字
  • \b 表示单词边界,确保匹配的时间字符串前后没有其他数字或字符,在字符串首尾各一个

1、导入re模块:

python 复制代码
import re

2、使用re.search()函数查找字符串中是否包含指定的模式:

python 复制代码
import re
pattern = r'\d+'  # 匹配一个或多个数字
string = 'abc123def456'
result = re.search(pattern, string)
if result:
    print('找到匹配项:', result.group())
else:
    print('未找到匹配项')

3、使用re.findall()函数查找字符串中所有符合指定模式的子串

python 复制代码
import re
pattern = r'\d+'  # 匹配一个或多个数字
string = 'abc123def456'
result = re.findall(pattern, string)
print('找到的所有匹配项:', result)

4、使用re.sub()函数替换字符串中符合指定模式的子串:

python 复制代码
import re
pattern = r'\d+'  # 匹配一个或多个数字
replacement = 'NUM'
string = 'abc123def456'
result = re.sub(pattern, replacement, string)
print('替换后的字符串:', result)

5、使用re.split()函数根据指定模式分割字符串

python 复制代码
import re
pattern = r'\d+'  # 匹配一个或多个数字
string = 'abc123def456'
result = re.split(pattern, string)
print('分割后的字符串列表:', result)

6、使用re.compile()函数将正则表达式编译为一个模式对象,以便重复使用:

python 复制代码
import re
pattern = re.compile(r'\d+')  # 匹配一个或多个数字

7、使用re.escape()函数对特殊字符进行转义,以便在正则表达式中使用:

python 复制代码
import re
string = 'a.b*c?d+e|f{g}h[i]j^k$l'
escaped_string = re.escape(string)
print('转义后的字符串:', escaped_string)
相关推荐
明月_清风6 小时前
Python 装饰器前传:如果不懂“闭包”,你只是在复刻代码
后端·python
明月_清风6 小时前
打破“死亡环联”:深挖 Python 分代回收与垃圾回收(GC)机制
后端·python
ZhengEnCi1 天前
08c. 检索算法与策略-混合检索
后端·python·算法
明月_清风1 天前
Python 内存手术刀:sys.getrefcount 与引用计数的生死时速
后端·python
明月_清风1 天前
Python 消失的内存:为什么 list=[] 是新手最容易踩的“毒苹果”?
后端·python
Flittly2 天前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(3)TodoWrite (待办写入)
python·agent
千寻girling2 天前
一份不可多得的 《 Django 》 零基础入门教程
后端·python·面试
databook2 天前
探索视觉的边界:用 Manim 重现有趣的知觉错觉
python·动效
明月_清风2 天前
Python 性能微观世界:列表推导式 vs for 循环
后端·python
明月_清风2 天前
Python 性能翻身仗:从 O(n) 到 O(1) 的工程实践
后端·python