如何在Python中使用正则表达式进行字符串匹配和替换?
在Python中,你可以使用内置的re
模块来操作正则表达式。以下是一些基本的操作:
字符串匹配:
import re
pattern = r"example"
text = "This is an example."
match = re.search(pattern, text)
if match:
print("Match found:", match.group())
else:
print("No match found.")
字符串替换:
import re
pattern = r"example"
text = "This is an example."
replacement = "replacement text"
new_text = re.sub(pattern, replacement, text)
print("Original text:", text)
print("New text with replacement:", new_text)
这些例子展示了如何在Python中使用正则表达式进行字符串匹配和替换。
还没有评论,来说两句吧...