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

相关推荐
李可以量化3 小时前
redis-py 从了解到精通(三):Redis Key 核心操作函数详解(上)
python
卷无止境3 小时前
FastAPI 实现 SSO,从协议原理到生产级落地
后端·python·fastapi
卷无止境4 小时前
FastAPI 与 RustFS 集成指南
后端·python·fastapi
青 春 记 忆4 小时前
零基础入门python25:新增账目——Decimal、日期和输入校验
python·后端开发
北风toto4 小时前
阿里云 MaxCompute通过python脚本调用odps流程和执行sql
python·阿里云·odps
ShineWinsu4 小时前
对于TRAE中配置Qt的解析
开发语言·c++·ide·vscode·qt·ai·trae
蒸蒸yyyyzwd4 小时前
AI软件开发面试gpt模拟学习笔记
人工智能·gpt·面试
qq_161111274 小时前
Pillow项目深度解析:Python图像处理的终极武器
图像处理·python·pillow·开源库·历史解析
梅孔立4 小时前
Pi-Agent 终极极简配置文档(Java+Vue+Python爬虫 4-5千文件项目)
java·vue.js·python
李可以量化4 小时前
Redis Client 从了解到精通(二)下:String 类型进阶操作全解
redis·git·python·量化交易·qmt