繁体   English   中英

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

[英]How to Perform Operations on Regex Backreference Matches in Javascript?

在javascript中,我有一个包含数字的字符串,我想将值递增一。

例:

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}"}

使用带有函数的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."

找到了。

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)

本来应该猜到一个匿名函数会起作用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM