我是编码新手,有一个函数可以用另一个字符串替换子字符串,并使用以下正则表达式来查找子字符串:
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');
要使用正则表达式模式正确匹配包含括号
( )
的子字符串,您需要转义括号,因为它们是正则表达式语法中的特殊字符。这是因为括号用于在正则表达式中定义组。以下是您可以修改 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
。