javascript - 在正则表达式中重新替换
问题描述
我正在创建一个函数,将字符串替换为
~(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~
解决方案
所以你需要一个不同的正则表达式规则。您不想更换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~" ) )
推荐阅读
- ascii - 在 Asciidoc 中使用突出显示的源代码创建表
- angular - 无法使用带有 angular5 和 ionic 的传单实时插件
- wordpress - 我如何循环 WordPress 特定的帖子
- import - AttributeError:模块“pytest”没有“来自sklearn.model_selection import cross_val_score”的属性“mark”
- codenameone - 如何配置代号项目以安装在 Android 的外部存储上
- mysql - Mysql离开连接并连接?
- ssh - 使用 SSH 密钥将 BitBucket 部署到远程服务器
- asp.net-mvc - MVC5 中的 WWWROOT
- python-3.x - 无法在 python3 中导入 pyPyrTools
- reactjs - 将数据从父级传递给子级reactjs?