import re
# 示例1:使用re.match()进行匹配,只匹配字符串的开头
match_result = re.match(r'hello', 'hello world')
if match_result:
print("Match found:", match_result.group()) # 输出: Match found: hello
else:
print("No match")
# 示例2:使用re.search()进行匹配,可以在整个字符串中查找
search_result = re.search(r'world', 'hello world')
if search_result:
print("Search found:", search_result.group()) # 输出: Search found: world
else:
print("No match")
# 示例3:使用re.findall()查找所有匹配项
findall_result = re.findall(r'\d+', '12 drummers drumming, 11 pipers piping, 10 lords a-leaping')
print("Find all numbers:", findall_result) # 输出: Find all numbers: ['12', '11', '10']
# 示例4:使用re.sub()进行替换
sub_result = re.sub(r'\d+', 'number', '12 drummers drumming, 11 pipers piping, 10 lords a-leaping')
print("Substitute numbers with 'number':", sub_result) # 输出: Substitute numbers with 'number': number drummers drumming, number pipers piping, number lords a-leaping
None
。None
。这些示例展示了 Python 的 re
模块中常用的功能。
上一篇:计算机python语言
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站