2012-03-06 55 views
2

我試圖掩蓋「123-12-1234」到「XXX-XX-1234」的SSN。我能夠實現使用下面的代碼。使用正則表達式掩蔽SSN

string input = " 123-12-1234 123-11-1235 "; 

Match m = Regex.Match(input, @"((?:\d{3})-(?:\d{2})-(?<token>\d{4}))"); 

while (m.Success) 
{ 
    if (m.Groups["token"].Length > 0) 
    { 
     input = input.Replace(m.Groups[0].Value,"XXX-XX-"+ m.Groups["token"].Value); 
    } 
    m = m.NextMatch(); 
} 

有沒有更好的方法來使用Regex.Replace方法在一行中完成它。

回答

4

你可以嘗試以下方法:

string input = " 123-12-1234 123-11-1235"; 

string pattern = @"(?:\d{3})-(?:\d{2})-(\d{4})"; 
string result = Regex.Replace(input, pattern, "XXX-XX-$1"); 

Console.WriteLine(result); // XXX-XX-1234 XXX-XX-1235 
+0

像魅力:)工作 – Nayan 2012-03-06 11:35:18

0

如果您打算做掩蓋,你應該考慮一些是否使用正則表達式編譯或不是很多。

使用它們會在第一次運行應用程序時造成一些延遲,但隨後它們會運行得更快。

此外,還應考慮選擇靜態與正則表達式的實例。

我發現下面是最有效的

public class SSNFormatter 
{ 
    private const string IncomingFormat = @"^(\d{3})-(\d{2})-(\d{4})$"; 
    private const string OutgoingFormat = "xxxx-xx-$3"; 

    readonly Regex regexCompiled = new Regex(IncomingFormat, RegexOptions.Compiled); 

    public string SSNMask(string ssnInput) 
    { 
     var result = regexCompiled.Replace(ssnInput, OutgoingFormat); 
     return result; 
    } 
} 

有六種方法的正則表達式檢查/掩蔽here的比較。