【问题标题】:Regex: replace words from a list of words正则表达式:替换单词列表中的单词
【发布时间】:2022-12-10 10:59:36
【问题描述】:

我是正则表达式的新手。我使用具有正则表达式功能的 Android 文本编辑器进行搜索和替换。该应用程序具有用于搜索字符串和替换字符串的对话框。它工作得很好。

我有一个 10 个单词的列表,其中 10 个单词用于替换。正则表达式可以一次性完成替换吗?例如,搜索:(aa)、(bb)。替换为:xx,yy。 谢谢

作为一个新手,我不知道从哪里开始。但是如果正则表达式不能,我有我的 PHP 代码可以做到这一点。我也知道,Word 中的宏可以完成任务。

【问题讨论】:

    标签: javascript regex list regexp-replace


    【解决方案1】:

    是的,可以使用正则表达式搜索多个单词并一次性将它们替换为相应的替换项。在大多数正则表达式中,您可以使用 | 字符来指定多个替代模式,然后使用捕获组来引用替换字符串中的匹配模式。

    例如,要搜索单词“aa”和“bb”并分别替换为“xx”和“yy”,可以使用以下正则表达式:

    (aa)|(bb)
    

    此正则表达式将匹配“aa”或“bb”,并在捕获组中捕获匹配的词。然后,在替换字符串中,您可以使用语法 $1$2 分别引用来自第一和第二捕获组的捕获文本。例如,替换字符串可以是:

    $1xx$2yy
    

    这会将“aa”替换为“xx”,将“bb”替换为“yy”。

    请注意,使用捕获组并在替换字符串中引用它们的确切语法可能会有所不同,具体取决于您使用的正则表达式风格。有关更多详细信息,请参阅您的特定正则表达式风格的文档。

    或者

    您可以使用匹配任何要替换的单词的正则表达式模式,并使用 re.sub() 函数执行替换。

    这是一个如何在 Python 中工作的示例:

    import re
    
    # The list of words to search for
    search_words = ["aa", "bb"]
    
    # The list of replacement words
    replacement_words = ["xx", "yy"]
    
    # The string to search and replace in
    string = "This is a test string with the words aa and bb"
    
    # Use a regex pattern that matches any of the search words, and use the `re.sub()` function to perform the replacements
    regex_pattern = re.compile("|".join(search_words))
    replaced_string = regex_pattern.sub(lambda m: replacement_words[search_words.index(m.group(0))], string)
    
    # Print the replaced string
    print(replaced_string)
    

    此代码将打印以下输出:

    This is a test string with the words xx and yy
    

    请注意,您可以在其他支持正则表达式的编程语言(例如 PHP)中使用类似的方法。

    【讨论】:

      猜你喜欢
      • 2020-01-06
      • 1970-01-01
      • 1970-01-01
      • 2015-09-03
      • 2019-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多