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

相关推荐
qq_2837200511 分钟前
MySQL 50+ 道高频面试题(含详细答案)
mysql·面试·高频
tgethe1 小时前
java并发——1
java·开发语言·面试
郑州光合科技余经理1 小时前
海外O2O系统源码剖析:多语言、多货币架构设计与二次开发实践
java·开发语言·前端·小程序·系统架构·uni-app·php
威联通网络存储4 小时前
某高端显示面板制造企业:基于威联通 TS-h2490FU 的 AOI 检测数据治理实践
python·制造
前端摸鱼匠7 小时前
【AI大模型春招面试题11】什么是模型的“涌现能力”(Emergent Ability)?出现条件是什么?
人工智能·算法·ai·自然语言处理·面试·职场和发展
globaldomain8 小时前
什么是用于长距离高速传输的TCP窗口扩展?
开发语言·网络·php
沈阳信息学奥赛培训8 小时前
#undef 指令 (C/C++)
c语言·开发语言·c++
2401_873204658 小时前
分布式系统安全通信
开发语言·c++·算法
FreakStudio8 小时前
不用装软件!这款MicroPython浏览器 IDE :让你在手机上也能调试树莓派 Pico
python·单片机·嵌入式·电子diy·tinyml
swipe8 小时前
把 JavaScript 原型讲透:从 `[[Prototype]]`、`prototype` 到 `constructor` 的完整心智模型
前端·javascript·面试