正则表达式替换前5个数字,无论它们之间有什么关系? [英] Regex for replacing first 5 numbers, irrespective of anything between them?
问题描述
我正在努力实现以下匹配
I'm trying to achieve the following match
输入
123-45-6789
123456789
1234
Reg Ex(s)尝试输出:
\d{5}
123-45-6789
123-45-6789
12345 6789
1234
\d{2,3}
123 - 45 - 678 9
123-45-6789
123456789
123 4
\d{3}-{0,1}\d{2}
123-45 -6789
12345 6789
1234
我需要供应这个正则表达式替换方法,我不希望替换 - ,它应该只替换前5位而不改变格式:
I need to supply this regex to replace method, and I don't want the "-" to be replaced, it should only replace the first 5 digits without changing the format:
预期产出
123 - 45 -6789
123-45-6789
12345 6789
1234
编辑
在上面的示例输出中:
1>所有都是与全球正则表达式匹配
2>加粗数字仅预期匹配
1> all are matched with global regex 2> the bolded digits are only expected to be matched
目的
我需要掩盖SSN,例如:444-55-6666变成### - ## - 6666而444556666变成##### 6666。不妨碍格式化。
I need to mask SSN, eg: 444-55-6666 becomes ###-##-6666 and 444556666 becomes #####6666. Without hampering the format.
推荐答案
您希望匹配并替换前五位数字:
You want to match and replace those first five digits:
var str = `123-45-6789
123456789
1234
`
console.log(str.replace(/^(\D*\d\D*){5}/gm, function(match) {
return match.replace(/\d/g, '*');
}))
这篇关于正则表达式替换前5个数字,无论它们之间有什么关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!