如何在Python中使用正则表达式?实例解析
在Python中,你可以使用内置的re
模块来处理正则表达式。以下是一些基本的例子:
- 匹配:通过
= re.match(pattern, string)
检查字符串是否以特定模式开始。
import re
pattern = r'^Hello'
string = 'Hello World'
match = re.match(pattern, string)
if match:
print("Match found!")
else:
print("No match found.")
- 搜索:使用
= re.search(pattern, string)
在字符串中查找第一个与给定模式匹配的子串。
search_result = re.search(pattern, string)
if search_result:
print(f"Found match at index {search_result.start()}.")
else:
print("No match found.")
- 替换:使用
= re.sub(pattern, replacement, string)
在字符串中找到所有匹配给定模式的子串,并用提供的替代字符串替换它们。
substituted_string = re.sub(pattern, "REPLACED", string)
print(substituted_string)
以上就是Python中使用正则表达式的简单示例。
还没有评论,来说两句吧...