-2

I have a web API that has to log the request body if an exception happens.
Since there are first name and last name properties in the body, I have to anonymize them which I'm trying to achieve using regex.

requestBody = Regex.Replace(requestBody, @"""FirstName"":""(.+)""", match => $@"""FirstName"":""{match.Groups[1].ToString()[0]}***""");
requestBody = Regex.Replace(requestBody, @"""LastName"":""(.+)""", match => $@"""LastName"":""{match.Groups[1].ToString()[0]}***""");

Unfortunately, after the first replace, everything else in the request body is gone (probably due to the .+ but shouldn't this stop when it finds the first "?

A request body looks like that:

{ Person":{"Gender":"Male","FirstName":"Aaron","LastName":"Example","BirthDate":"1990-09-02T00:00:00.000Z" }}

And I want the first name to be "A***" and the last name to be "E***".

What am I doing wrong and is there a more elegant way?

Thanks in advance!

Akif
  • 7,098
  • 7
  • 27
  • 53
xeraphim
  • 4,375
  • 9
  • 54
  • 102

1 Answers1

0

That's because .+ is greedy: it takes as much as it can until any ", so it greedily takes the very last " of your request.

To make it non-greedy (= lazy) append a '?' to the quantifier, like this:

"FirstName":"(.+?)"
Thomas
  • 432
  • 3
  • 13
  • And the "more elegant" question... maybe use this regex "FirstName":".(.+?)" (note the extra '.'), then you can just replace the group by "xxx" and omit the [0]-stuff. – Thomas Dec 07 '20 at 15:27