繁体   English   中英

替代正面看背后

[英]Alternative to positive look behind

我刚刚发现正面的外观在旧版浏览器中不起作用,我在 IE11 上遇到了这个问题,即Unexpected quantifier

正则表达式: /(?<=\d{4})\d(?=\d{4})/g

输入: const string = 4444333322221111;

string.replace(/(?<=\d{4})\d(?=\d{4})/g, "#");

预期结果: 4444########1111

此正则表达式的任何替代方法都会有所帮助。

您可以使用 function 和索引,并将前四位数字替换为 digit 或替换为#

 var string = '4444333322221111'; console.log(string.replace(/\d(?=\d{4})/g, function (v, i) { return i < 4? v: '#'; }));

使用切片字符串更新。

 var string = '4444333322221111', result = string.slice(0, 4) + string.slice(4, -4).replace(/./g, '#') + string.slice(-4); console.log(result)

如果你的字符串只包含数字,你真的不需要正则表达式,你只需要几个字符串操作方法:

 // Adapted from https://stackoverflow.com/a/5450113/3832970, count will always be positive here function strRepeat(pattern, count) { var result = ''; while (count > 1) { if (count & 1) result += pattern; count >>= 1, pattern += pattern; } return result + pattern; }; var string = "4444333322221111"; console.log( string.substring(0,4) + strRepeat("#", string.length-8) + string.slice(-4) )

如果您需要在较长的字符串中屏蔽用四位数字括起来的数字,您可以使用:

 function strRepeat(pattern, count) { var result = ''; while (count > 1) { if (count & 1) result += pattern; count >>= 1, pattern += pattern; } return result + pattern; }; var string = "111109876543210000 abc 1234012345678904321"; console.log( string.replace(/\d{9,}/g, function(match) { return match.substr(0,4) + strRepeat("#", match.length-8) + match.slice(-4); }) )

这里,

  • /\d{9,}/g匹配所有出现的九个或更多数字
  • function(match) {...} - 采用正则表达式匹配的回调方法,您可以在此处操作 output
  • match.substr(0,4) + "#".repeat(match.length-8) + match.slice(-4) - 连接前 4 位数字,然后附加需要替换为#的数字,并且然后添加剩余的 4 位数字。

如果需要,您可以使用捕获组制作正则表达式模式,它会使回调方法更小,但会使正则表达式更长:

 function strRepeat(pattern, count) { var result = ''; while (count > 1) { if (count & 1) result += pattern; count >>= 1, pattern += pattern; } return result + pattern; }; var string = "111109876543210000 abc 1234012345678904321"; console.log( string.replace(/(\d{4})(\d+)(\d{4})/g, function($0, $1, $2, $3) { return $1 + strRepeat("#", $2.length-8) + $3; }) )

在这里, (\d{4})(\d+)(\d{4})模式会将 4 位数字捕获到第 1 组( $1 )中,然后将 1+ 位捕获到第 2 组( $2 )中,然后再捕获 4 位数字将被捕获到第 3 组 ( $3 )。

您的输入字符串看起来像支付卡号。 您不需要正则表达式,您可以使用简单的字符串处理函数,如String.substring()和字符串连接。

例如:

 const str = '1111222233334444'; const masked = str.substring(0, 4) + '#'.repeat(str.length - 8) + str.substring(str.length - 4) console.log(masked);

正则表达式解决方案不需要使用查找:

 const str = '1111222233334444'; const masked = str.replace(/^(\d{4})(\d*)(\d{4})$/, `$1${"#".repeat(str.length - 8)}$3`); console.log(masked);

暂无
暂无

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

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