在Python中使用正则表达式进行文本搜索与替换案例

原创 ﹏ヽ暗。殇╰゛Y 2025-03-23 22:27 79阅读 0赞

在Python中,我们可以使用内置的re模块来处理正则表达式。以下是一些基本的搜索和替换的例子:

  1. 搜索

    • 找出所有以”hello”开头的字符串:

      1. import re
      2. text = "Hello world! Hello again."
      3. pattern = r'^Hello ' # ^ denotes start of line
      4. matches = re.findall(pattern, text)
      5. print(matches) # Output: ['Hello world!', 'Hello again.']
  2. 替换

    • 替换所有出现的”world”为”Universe”:

      1. import re
      2. text = "Hello world! Hello again."
      3. pattern = r'world'
      4. new_text = re.sub(pattern, "Universe", text)
      5. print(new_text) # Output: "Hello Universe! Hello again."

以上就是使用Python和正则表达式进行文本搜索与替换的基本示例。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,79人围观)

还没有评论,来说两句吧...

相关阅读