How to replace a number within a string by itself + 1?
我有一个字符串,例如"我们有一个 foobar,每个 bar 最多可以提供 20 个 foo"。我想用
"We have a foobar which can provide <21 foo per bar."
我想过类似的事情:
1 | string.replace("/maximum\\sof\\s\\d+/ig", `<${$1++}`) |
但我不能让它作为 $1 只反向引用整个捕获组而不是单个数字。我也在字符串格式方面挣扎。
可以使用回调函数和捕获组
1 | maximum\\sof\\s(\\d+) |
-
maximum\\sof\\s - 匹配maximum of -
(\\d+) - 匹配一位或多位数字(捕获组 1)
在回调中,我们可以使用捕获的组替换我们想要的任何额外内容
1 2 3 4 | let str ="We have a foobar which can provide a maximum of 20 foo per bar." let replaced = str.replace(/maximum\\sof\\s(\\d+)/ig, (_, g1) => '<' + (+g1+1)) console.log(replaced) |
替换可以使用一个函数:
1 2 3 4 5 6 7 | let input ="We have a foobar which can provide a maximum of 20 foo per bar."; console.log( input.replace(/(?:\\ba )?maximum of ([0-9]+)\\b/, function (all, max) { return"<" + (max / 1 + 1); }) ); |
这匹配