如何在Python中利用正则表达式?示例
在Python中,你可以使用内置的re
模块来操作正则表达式。以下是一些基本的示例:
- 匹配:使用
=match(pattern, string)
函数进行匹配。
import re
# 正则模式
pattern = r'hello'
# 待匹配字符串
string = 'Hello, world! Hello again.'
# 匹配结果
match_obj = re.search(pattern, string)
if match_obj:
print("Match found:", match_obj.group(0)))
else:
print("No match found.")
- 替换:使用
=re.sub(pattern, replacement, string)
函数进行替换。
# 替换模式
replacement = r'hi'
# 使用替换后的字符串
new_string = 'Hello, world! Hello again.'
# 替换结果
new_string = re.sub(pattern, replacement, new_string)
print("New string after substitution:", new_string)
- 分割:使用
=re.split(pattern, string, maxsplit=0))
函数进行分割。
# 分割模式
separator = ', ' # 使用逗号和空格作为分隔符
# 待分割字符串
string = "Hello, world! Hello again."
# 分割结果
result = re.split(separator, string)
print("Split result:", result)
以上就是如何在Python中使用正则表达式的基本示例。
还没有评论,来说两句吧...