简体   繁体   中英

Regex for match and replace substring

We have logging functionality to log all the requests and now I want to hide some sensitive data from the request body.

string body = null;

using (var reader = new StreamReader(request.InputStream))
{
    request.InputStream.Seek(0L, SeekOrigin.Begin);
    body = reader.ReadToEnd();
}

if (!string.IsNullOrWhiteSpace(body))
{
    _logger.NameValueLogger.Add("body", RemoveSensitiveData(body));
}

Example for Body content:

"Id=12345&Id=&Name=TestName&AddressLine1=1232+test+&AddressLine2=sdf&City=abcd"

Now in RemoveSensitiveData() I want to search for Name and replace the name value "TestName" to "*****"

Also if there are any other fields I want to hide along with name, I have to replace them too.

Can anyone please suggest best approach to handle this?

This should do it:

string RemoveSensitiveData(string value) => Regex.Replace(value, "((^|&)(Name|OtherSensitiveData)=)[^&]+", m => m.Groups[1].Value + "*****")

edit: added (^|&) ensure full match

If you want to "mask" some parameter with a fixed amount of asterisks you may use a simple Regex.Replace with no MatchEvaluator:

string RemoveSensitiveData(string value) => 
    Regex.Replace(value, "((?:&|^)(?:Name|OtherSensitiveData)=)[^&]+", "$1*****")

If you plan to replace with the same amount of asterisks use

string RemoveSensitiveData(string value) =>
    Regex.Replace(value, "((?:&|^)(?:Name|OtherSensitiveData)=)([^&]+)", m =>
        $"{m.Groups[1].Value}{new String('*', m.Groups[2].Value.Length)}")

Regex details

  • ((?:&|^)(?:Name|OtherSensitiveData)=) - Group 1:
    • (?:&|^) - a non-capturing group matching either a & char or start of string (it can be replaced with (?<![^&]) )
    • (?:Name|OtherSensitiveData) - a non-capturing group matching either Name or OtherSensitiveData substrings
    • = - an equal sign
  • ([^&]+) - Group 2: any 1+ chars other than & .

See the C# demo:

var value = "Id=12345&Id=&Name=TestName&AddressLine1=1232+test+&AddressLine2=sdf&City=abcd";
Console.WriteLine(Regex.Replace(value, "((?:&|^)(?:Name|OtherSensitiveData)=)[^&]+", "$1*****"));
// => Id=12345&Id=&Name=*****&AddressLine1=1232+test+&AddressLine2=sdf&City=abcd
Console.WriteLine(Regex.Replace(value, "((?:&|^)(?:Name|OtherSensitiveData)=)([^&]+)", m =>
        $"{m.Groups[1].Value}{new String('*', m.Groups[2].Value.Length)}"));
// => Id=12345&Id=&Name=********&AddressLine1=1232+test+&AddressLine2=sdf&City=abcd

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM