如何在JavaScript中对正则表达式的反向引用匹配执行操作?

6
在Javascript中,我有一个包含数字的字符串,我想将这些数字增加1。
例如:
var string = "This is a string with numbers 1 2 3 4 5 6 7 8 9 10";

var desiredResult = "This is a string with numbers 2 3 4 5 6 7 8 9 10 11";

使用正则表达式,能否对匹配的反向引用进行操作(在这种情况下为加法)?

我发现了一个类似的问题,它使用Ruby:

string.gsub(/(\d+)/) { "#{$1.to_i + 1}"}
2个回答

7

使用 string.replace 方法,并将一个函数作为第二个参数:

var s1 = "This is a string with numbers 1 2 3 4 5 6 7 8 9 10";
var s2 = s1.replace(/\d+/g, function(x) { return Number(x)+1; });
s2; // => "This is a string with numbers 2 3 4 5 6 7 8 9 10 11"

请注意,如果您使用匹配组,则该函数的第一个参数将是整个匹配,每个后续参数将是编号的匹配组。
var x = "This is x1, x2, x3.";
var y = x.replace(/x(\d+)/g, function(m, g1) {
  return "y" + (Number(g1)+1);
});
y; // => "This is y2, y3, y4."

我最终在我的实际代码中使用了arguments[n](而不是x),因为我有多个反向引用。 - Lance Rushing

1

找到了。

var string = "This is a string with Numbers 1 2 3 4 5 6 7 8 9 10";
var desiredResult = "This is a string with Numbers 2 3 4 5 6 7 8 9 10 11";
var actualResult = string.replace(/([0-9]+)/g, function() {
    return parseInt(arguments[1])+1 
});
console.log(actualResult)

应该猜到匿名函数会起作用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接