使用正则表达式搜索带有 () 的文本并将其替换为其他文本

问题描述 投票:0回答:1

我是编码新手,有一个函数可以用另一个字符串替换子字符串,并使用以下正则表达式来查找子字符串:

regex = new RegExp(substring, "g");
.
.
.
return fullString.replace(regex, function (match, index) {
    if (some condition) {
          // Return the original match without replacing
          return match;
        } else {
          // Return the replaceString
          return replaceString;
        }
} );

该函数适用于所有子字符串,除了带有 () 的下标。 示例:

适用于:

hello hi
hi
bye

不适用于:

hello (hi)

如何解决这个问题?请建议正确的正则表达式,但不建议使用其他方法。我无法对代码进行大量更改。

尝试了以下正则表达式模式,但它不起作用:

正则表达式 = new RegExp(

\\b${substring}(?:[^)]+\\b|\\(([^)]+)\\b)
, 'g');

html regex string regexp-replace nsregularexpression
1个回答
0
投票

要使用正则表达式模式正确匹配包含括号

( )
的子字符串,您需要转义括号,因为它们是正则表达式语法中的特殊字符。这是因为括号用于在正则表达式中定义组。以下是您可以修改 RegExp 构造来处理此问题的方法:

  • 首先,转义子字符串中的所有特殊字符。
  • 然后使用修改后的子字符串创建正则表达式模式。

这是一个例子:

function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');  // $& means the whole matched string
}

function replaceSubstring(fullString, substring, replaceString) {
  let escapedSubstring = escapeRegExp(substring);
  let regex = new RegExp(escapedSubstring, "g");

  return fullString.replace(regex, function(match) {
    if (/* some condition */) {
      return match;  // Return the original match without replacing
    } else {
      return replaceString;  // Return the replaceString
    }
  });
}

此函数转义

substring
中的特殊正则表达式字符(包括括号),然后使用此转义的
substring
创建一个正则表达式,用于在
fullString
中匹配和替换。该函数根据给定条件将出现的
substring
替换为
replaceString

© www.soinside.com 2019 - 2024. All rights reserved.