Reputation: 1351
I have below Json which is having -INF in its value and I need to replace INF with "Infinity". Below is the sample JSON and REGEX which does the trick for me. I am looking for ways I can optimize the below method and if I can use a single Regex instead of two.
Sample Json : "Power_dB":[-INF,-1000,-1000,-1000,-INF,-INF,-INF,-INF]
My code:
var pattern = @"-(INF){1},";
var secondPattern = @"-(INF){1}\]";
string replacement = "-Infinity,";
string secondreplacement = "-Infinity]";
string result = Regex.Replace( json, pattern, replacement );
result = Regex.Replace( result, secondPattern, secondreplacement );
var settings = new JsonSerializerSettings() { FloatFormatHandling = FloatFormatHandling.Symbol };
var data = JsonConvert.DeserializeObject<JObject>( result, settings ) ;
Above code gives me desired output as below:
"Power_dB":["-INFINITY",-1000,-1000,-1000,"-INFINITY","-INFINITY","-INFINITY","-INFINITY"]
Upvotes: 0
Views: 61
Reputation: 38785
I would suggest changing your expression to this:
-INF(?=[,\]])
Breaking it down:
-INF
- Match the literal "-INF"(?=something)
- Positive lookahead. The expression only matches if this also matches, but this doesn't capture.[,\]]
- Match ,
or ]
. In this case we have no modifier after it so it will only match a single character.Then you can simply replace the matched part with this:
-Infinity
C# code:
var regex = new Regex(@"-INF(?=[,\]])");
string input = "\"Power_dB\":[-INF,-1000,-1000,-1000,-INF,-INF,-INF,-INF]";
string result = regex.Replace(input, "-Infinity");
Console.WriteLine(result);
Upvotes: 3