如何在字符串中屏蔽SSN?
我有以下情况
string str1 = "asdasfasdfasdf sfhagfdad SSN:123456789";
我的所需输出"asdasfasdfasdf sfhagfdad SSN:*********"
我尝试了以下代码
Regex ssnRegex = new Regex("(?:\bSSN:\b)(?:[0-9]{3})(?:[0-9]{2})(?:[0-9]{4})");
string formattedSSN = ssnRegex.Replace(t1, "SSN:-XXX-XX-XXXX");
我想我错过捕获“SSN:”你能否告诉我如何获得上述输出
答案 0 :(得分:2)
为什么不使用String.Replace
?
string str1 = "asdasfasdfasdf sfhagfdad SSN:123456789";
//Get starting position
int position = str1.IndexOf("SSN:") + 4;
//Extract social
string ssn = str1.Substring(position, 9);
//Update string
str1 = str1.Replace(ssn, "XXX-XX-XXXX");
答案 1 :(得分:1)
Regex.Replace("asdasfasdfasdf sfhagfdad SSN:123456789", @"\d{3}[-]?\d{2}[-]?\d{4}", "***")
output: "asdasfasdfasdf sfhagfdad SSN:***"
Regex.Replace("asdasfasdfasdf sfhagfdad SSN:123456789", @"^*SSN:\d{3}[-]?\d{2}[-]?\d{4}", "SSN:***")
output: "asdasfasdfasdf sfhagfdad SSN:***"