我认为你不应该依赖正则表达式来完成这类任务,因为它会过于复杂,因此速度很慢。无论如何,如果您的表达式是正确的(即,对于每个"|code"
有 a"code|"
并且没有嵌套code
标签),您可以试试这个:
var n = str.replace(/to(?!(?:\|(?!code)|[^\|])*code\|)/g, "2");
不仅复杂,而且难以维护。在这些情况下,最好的办法是将字符串拆分为块:
var chunks = [], i, p = 0, q = 0;
while ((p = str.indexOf("|code", p)) !== -1) {
if (q < p) chunks.push(str.substring(q, p));
q = str.indexOf("code|", p);
chunks.push(str.substring(p, p = q = q + 5));
}
if (q < str.length) chunks.push(str.substring(q));
// chunks === [" Would you like to have responses to your questions ",
// "|code Would you like to have responses to your questions code|",
// " Would you like to have responses to your questions "]
注意:str.replace("to", "2")
不会替换所有出现的,而"to"
只会替换第一个。