在我的ruby脚本中,我有一个正则表达式:
regex = /(^|[^\d])\d{8,15}(?!\d)/g;
和一个字符串
var str="jshbfjhsgf 123 1234567890 4567890123 hhrrwt";
如果我这样做
str.replace(regex,"xxxxxxxxxx");
输出将是:
"jshbfjhsgf 123 xxxxxxxxxx xxxxxxxxxx hhrrwt";
但我想要这样的事情:
"jshbfjhsgf 123 1xxxxxxxx0 4xxxxxxxx3 hhrrwt";
答案 0 :(得分:3)
Regex(string, string)构造函数的动态范围:
function digitMask(min, max, str, replacement) {
var regex = new RegExp("(^|[^\\d])(\\d)(\\d{" + min + "," + max + "})(\\d)(?!\\d)","g");
return str.replace(regex, function (match, c1, c2, c3, c4, index, source) {
var length = c3.length;
var mask = "";
for (var i = 0; i < length; i++) mask += replacement;
return match.replace(c3, mask);
});
}
var result = digitMask(8, 14, "start 123 1234567890123123567890 4567890123 end", "-");
console.log(result)
// outputs "start 123 1--------------3 4--------3 end"
&#13;
第二个和第四个单个数字捕获组允许内部捕获和屏蔽相对于内部捕获的长度。