Python面试题:如何在 Python 中进行正则表达式操作?

在 Python 中,正则表达式操作可以通过 re 模块来实现。以下是一些常用的正则表达式操作和示例:

1. 导入模块

python 复制代码
import re

2. 常见操作和示例

a. 匹配

使用 re.match() 来检查字符串的开头是否匹配某个模式。

python 复制代码
pattern = r'\d+'  # 匹配一个或多个数字
string = '123abc'
match = re.match(pattern, string)
if match:
    print("Match found:", match.group())
else:
    print("No match found")
b. 搜索

使用 re.search() 在整个字符串中搜索模式。

python 复制代码
pattern = r'\d+'
string = 'abc123def'
search = re.search(pattern, string)
if search:
    print("Search found:", search.group())
else:
    print("No match found")
c. 查找所有匹配项

使用 re.findall() 找到字符串中所有非重叠的匹配项。

python 复制代码
pattern = r'\d+'
string = 'abc123def456ghi789'
matches = re.findall(pattern, string)
print("All matches found:", matches)
d. 替换

使用 re.sub() 替换字符串中所有匹配的部分。

python 复制代码
pattern = r'\d+'
replacement = '#'
string = 'abc123def456ghi789'
new_string = re.sub(pattern, replacement, string)
print("Replaced string:", new_string)
e. 拆分

使用 re.split() 根据匹配的模式拆分字符串。

python 复制代码
pattern = r'\d+'
string = 'abc123def456ghi789'
split_list = re.split(pattern, string)
print("Split result:", split_list)

3. 示例总结

python 复制代码
import re

# 1. 匹配
pattern = r'\d+'
string = '123abc'
match = re.match(pattern, string)
if match:
    print("Match found:", match.group())
else:
    print("No match found")

# 2. 搜索
string = 'abc123def'
search = re.search(pattern, string)
if search:
    print("Search found:", search.group())
else:
    print("No match found")

# 3. 查找所有匹配项
string = 'abc123def456ghi789'
matches = re.findall(pattern, string)
print("All matches found:", matches)

# 4. 替换
replacement = '#'
new_string = re.sub(pattern, replacement, string)
print("Replaced string:", new_string)

# 5. 拆分
split_list = re.split(pattern, string)
print("Split result:", split_list)

以上是 Python 中进行正则表达式操作的一些基本方法和示例。正则表达式非常强大,可以用来处理复杂的字符串匹配和操作需求。

相关推荐
折果34 分钟前
如何在vue项目中封装自己的全局message组件?一步教会你!
前端·面试
HenryLin36 分钟前
美股量化分析系统 - 模块调用流程文档
python
跟橙姐学代码38 分钟前
一文读懂 Python 的 JSON 模块:从零到高手的进阶之路
前端·python
躺不平的小刘1 小时前
从YOLOv5到RKNN:零冲突转换YOLOv5模型至RK3588 NPU全指南
linux·python·嵌入式硬件·yolo·conda·pyqt·pip
前端小巷子1 小时前
Vue3的渲染秘密:从同步批处理到异步微任务
前端·vue.js·面试
文火冰糖的硅基工坊1 小时前
[激光原理与应用-317]:光学设计 - Solidworks - 草图
开发语言·python·信息可视化·系统架构
草莓熊Lotso2 小时前
【C语言强化训练16天】--从基础到进阶的蜕变之旅:Day10
c语言·开发语言·经验分享·算法·强化
草明2 小时前
docker stats 增加一列容器名称的显示
java·开发语言·docker
高级测试工程师欧阳2 小时前
python中selenium怎么使用
python·pandas
BertieHuang2 小时前
(一)深入源码,从 0 到 1 实现 Cursor
人工智能·python·程序员