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

相关推荐
qcwutv_5992 小时前
C++的std--ranges算法比较器
编程
2301_803875612 小时前
PHP 中处理会话数组时的类型错误解析与修复指南
jvm·数据库·python
m0_743623922 小时前
c++如何批量修改文件后缀名_std--filesystem--replace_extension【实战】
jvm·数据库·python
uyermw_4112 小时前
Redis Key 空间事件机制详解
编程
2401_873479402 小时前
如何利用IP查询定位识别电商刷单?4个关键指标+工具配置方案
开发语言·tcp/ip·php
我爱cope3 小时前
【从0开始学设计模式-10| 装饰模式】
java·开发语言·设计模式
viqiyc_2823 小时前
Rust的闭包中的互操作性
编程
2501_914245933 小时前
CSS如何处理CSS变量作用域冲突_利用特定类名重写变量值
jvm·数据库·python
菜鸟学Python3 小时前
Python生态在悄悄改变:FastAPI全面反超,Django和Flask还行吗?
开发语言·python·django·flask·fastapi
<-->3 小时前
Megatron(全称 Megatron-LM,由 NVIDIA 开发)和 DeepSpeed(由 Microsoft 开发)
人工智能·pytorch·python·深度学习·transformer