javascript regex - 查找由分隔符包围的子字符串

时间:2017-10-24 11:14:04

标签: javascript regex

我想替换substr所包含的所有子字符串$$

例如,考虑字符串

some substr $$This substr is enclosed by the delimiter$$ another substr

应该返回

some substr $$This newsubstr is enclosed by the delimiter$$ another substr

到目前为止我有什么

(?:\${2})[^$]*(substr)[^$]*(?=\${2})

编辑:分隔符中可以出现多个子字符串。

1 个答案:

答案 0 :(得分:2)

您需要首先匹配$$之间的所有子字符串,然后仅在这些匹配项中替换其他模式。

var s = "some substr $$This substr is enclosed by the delimiter$$ another substr";
var rxDollars = /\${2}[\s\S]*?\${2}/g;
var rxSubstr = /substr/g;
console.log(
  s.replace(rxDollars, function(match) { return match.replace(rxSubstr, "newsubstr"); })
);

另一项修改仅在$$之间的文本上运行替换。

var s = "some substr $$This substr is enclosed by the delimiter$$ another substr";
var rxDollars = /\${2}([\s\S]*?)\${2}/g;
var rxSubstr = /substr/g;
console.log(
  s.replace(rxDollars, function(match, group1) { return "$$" + group1.replace(rxSubstr, "newsubstr") + "$$"; })
);

您需要调整rxSubstr正则表达式以满足您的实际需求。

\${2}[\s\S]*?\${2}模式只匹配两个$个字符,然后任意0个字符尽可能少,直到最左边出现的双$个字符。