如何使用正则表达式屏蔽字符串中的SSN

时间:2011-07-26 18:50:28

标签: c# .net asp.net regex

如何在字符串中屏蔽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:”你能否告诉我如何获得上述输出

2 个答案:

答案 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:***"