首页 > 解决方案 > 在正则表达式中重新替换

问题描述

我正在创建一个函数,将字符串替换为

~(number)~.

现在假设我有一个字符串说 This is the replacement of ~26~ and ~524~. We still have 2 cadets left. Have2go for the next mission.2

我想将字符串中的所有 2 替换为,~86~但是当我这样做时, 2 in~26~~524~被替换为~~86~6~```~5~86~4~.

function replaceGameCoordinate() {
  var string = `This is the replacement of ~26~ and ~524~. We still have 2 cadets left. Have2go for the next mission.2`
  var replaceArr = ['2'];
  let patt = new RegExp(`${replaceArr[0]}`, 'gm')
  var newString = string.replace(patt, "~86~");
  console.log(newString);
}
replaceGameCoordinate();

预期的输出应该是:

This is the replacement of ~26~ and ~524~. We still have ~86~ cadets left. Have~86~go for the next mission.~86~

标签: javascriptregex

解决方案


所以你需要一个不同的正则表达式规则。您不想更换2. 你想更换2 when it's not next to another number or ~.

为了做到这一点,你可以使用lookaheads和lookbehinds(虽然我相信JS中的正则表达式还不支持lookbehinds,但至少有lookaheads):

const input = "This is the replacement of ~26~ and ~524~. We still have 2 cadets left. Have2go for the next mission.2";

const regex = /2(?![\d~])/gm // Means : "2 when it's not followed by a digit \d or a ~"

console.log( input.replace(regex, "~86~" ) )


推荐阅读