🛠️ToolsShed

查找与替换

使用纯文本或正则表达式模式查找和替换文本。

查找和替换工具让您在文本中搜索文本模式并将其替换为其他内容——全部在浏览器中完成,无需安装。虽然大多数文本编辑器都有内置的查找/替换功能,但当在缺少此功能的环境中工作,或需要共享或记录特定替换操作时,这个独立工具非常有用。

输入搜索词和替换文本,然后点击"全部替换"一次替换所有匹配项,或使用"替换下一个"逐个处理匹配项。支持区分大小写和不区分大小写的匹配、整词匹配(避免在"concatenate"中替换"cat"),以及用于复杂模式匹配的正则表达式模式。

正则表达式是查找和替换遵循模式而非精确文本的内容的强大方法。例如,您可以找到所有 YYYY-MM-DD 格式的日期并一次性将其重新格式化为 DD/MM/YYYY。此处支持的正则表达式语法遵循标准 JavaScript 正则表达式引擎。

常见问题

代码实现

import re

def find_replace(text: str, find: str, replace: str,
                 use_regex: bool = False, case_sensitive: bool = True) -> str:
    """Find and replace text, with optional regex and case-insensitive modes."""
    if use_regex:
        flags = 0 if case_sensitive else re.IGNORECASE
        return re.sub(find, replace, text, flags=flags)
    else:
        if case_sensitive:
            return text.replace(find, replace)
        else:
            # Case-insensitive plain string replace
            return re.sub(re.escape(find), replace, text, flags=re.IGNORECASE)

# Examples
text = "Hello World. Hello Python."
print(find_replace(text, "Hello", "Hi"))
# Hi World. Hi Python.

print(find_replace(text, r"\bHello\b", "Greetings", use_regex=True))
# Greetings World. Greetings Python.

print(find_replace(text, "hello", "Hi", case_sensitive=False))
# Hi World. Hi Python.

Comments & Feedback

Comments are powered by Giscus. Sign in with GitHub to leave a comment.