在Python中使用正则表达式进行文本搜索与替换案例
在Python中,我们可以使用内置的re
模块来处理正则表达式。以下是一些基本的搜索和替换的例子:
搜索:
找出所有以”hello”开头的字符串:
import re
text = "Hello world! Hello again."
pattern = r'^Hello ' # ^ denotes start of line
matches = re.findall(pattern, text)
print(matches) # Output: ['Hello world!', 'Hello again.']
替换:
替换所有出现的”world”为”Universe”:
import re
text = "Hello world! Hello again."
pattern = r'world'
new_text = re.sub(pattern, "Universe", text)
print(new_text) # Output: "Hello Universe! Hello again."
以上就是使用Python和正则表达式进行文本搜索与替换的基本示例。
还没有评论,来说两句吧...