Regex 使用正则表达式的SSN掩蔽
我试图将“123-12-1234”中的SSN屏蔽为“XXX-XX-1234”。我能够实现使用下面的代码Regex 使用正则表达式的SSN掩蔽,regex,Regex,我试图将“123-12-1234”中的SSN屏蔽为“XXX-XX-1234”。我能够实现使用下面的代码 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) {
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();
}
string input=“123-12-1234 123-11-1235”;
Match m=Regex.Match(输入,@“((?:\d{3})-(?:\d{2})-(?\d{4}));
while(m.Success)
{
如果(m.Groups[“token”].长度>0)
{
输入=输入.替换(m.Groups[0].值,“XXX-XX-”+m.Groups[“token”].值);
}
m=m.NextMatch();
}
是否有更好的方法使用Regex.Replace方法在一行中完成此操作。您可以尝试以下操作:
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
如果你要做大量的掩饰,你应该考虑一些是否使用编译的正则表达式。p> 当应用程序第一次运行时,使用它们会导致轻微的延迟,但随后它们会运行得更快
此外,还应考虑选择正则表达式的静态与实例 我发现以下是最有效的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;
}
}
对正则表达式检查/屏蔽的六种方法进行了比较