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 中进行正则表达式操作的一些基本方法和示例。正则表达式非常强大,可以用来处理复杂的字符串匹配和操作需求。

相关推荐
泡海椒14 小时前
Java 后端最优 PDF 导出方案:jquick-pdf 项目引入与快速测试
java·开发语言·pdf
XuCoder14 小时前
LangChain 模型调用:invoke、stream、batch 到底该怎么选?
面试
Evand J14 小时前
【MATLAB例程】二维Astar路径规划与AOA-TDOA定位仿真。完整代码,附下载链接。包运行成功,带中文注释
开发语言·matlab·路径规划·代码·定位·融合定位
XZ-07000114 小时前
week4-2-坐标轴
python
李永奉14 小时前
中科蓝讯SDK开发-耳机项目功耗问题排查教程
c语言·开发语言·嵌入式硬件·物联网·智能手机
Delta-delta14 小时前
Ubuntu MATE 24.04 + systemd 部署 LiteLLM + Open WebUI
python
金融大 k14 小时前
A股实时行情 API 接入指南:Python 覆盖行情、复权、基本面与 WebSocket
python·websocket·行情数据·行情 api
秋天的一阵风14 小时前
⚡2026 年了,十万级表格还只会「虚拟滚动」?难怪你的页面照样卡顿
前端·javascript·面试
生信大杂烩14 小时前
Xenium H&E空间原位可视化——细胞轮廓、基因表达与转录本可视化
python·算法·数据分析
秋天的一阵风14 小时前
🤖 AI写代码越跑越快,项目组件却越来越乱?一套工程闭环根治重复造轮子 ⚡
前端·面试·ai编程