开发者

How to mask SSN in a string using regex

How to mask SSN in a string ?

I am have the following scenario

string str1 = "asdasfasdfasdf sfhagfdad SSN:123456789";

my required output "asdasfasdfasdf sfhagfdad SSN:*********"

I tried the below code

Regex ssnRegex = new Regex("(?:\bSSN:\b)(?:[0-9]{3})(?:[0-9]{2})(?:[0-9]{4})");
string formattedSSN = ssnRegex.Replace(t1, "SSN:-XXX-XX-XXXX");

I think i am missing to capture "SSN开发者_运维技巧:" Could you please tell me how to get the above output


Why not just use 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");


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:***"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜