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

相关推荐
Ponp_1 小时前
用 StyleGAN2 做图像数据扩充实战
python·深度学习·生成对抗网络
怕浪猫3 小时前
2027 年最火的 AI 项目出炉,No.1 易主!
面试·架构·github
郝学胜-神的一滴4 小时前
Effective STL 条款15:注意字符串实现上的差异
java·开发语言·数据结构·c++·算法·visualstudio
sharemylove4 小时前
Java学习笔记 —— 面向对象专题
java·开发语言·笔记·学习·课程设计
圆心角4 小时前
Agent 上下文原理:为什么“记住”比“推理”更难
前端·面试·agent
富贵儿9985 小时前
NL2SQL 实践手记 08:SQL 没报错,答案为什么不对——从失败复盘到 Workflow 修复
数据库·python·sql·ai·自然语言处理·langchain
代码民工正电荷5 小时前
JAVA学习基础(一)
java·开发语言·学习
无巧不成书02187 小时前
最新 PyPI可信发布完整教程 GitHub Actions+OIDC零Token实现Python包自动化发布
python·自动化·github·pypi
星恒随风9 小时前
C++11 加餐(2)并发支持库——mutex、lock_guard、unique_lock 与死锁问题
开发语言·c++