'In C# string how to replace two chararacters ignoring a number

I am editing a serialized string becuase when deserilized it gives a parse error. so from a long Serialized string I want to edit "myVar\": \"0.2 mm" with "myVar\": \"0.2" if I use the follwoing code it works

string NewString = Serializedstring.Replace($"myVar\": \"0.2 mm", $"myVar\": \"0.2")

but my 0.2 is a varible that may change with every occurance. so all I want is to remove mm from the string "myVar\": \"0.2 mm"



Solution 1:[1]

I can recommend 2 alternate approaches

1)match what you can. var str = NewString.Replace(" mm,\"", ""); if your string is not going to have a space followed by mm" anywhere else that should be fine.

2)A safer option would be to deserialize it into something that can handle it (i assume your deserializing that property to a number currently) and then string replace the property and map it to what you need it.

Solution 2:[2]

There are lots of ways to do this, RegEx, String tokenisation, char array searching

RegEx is probably the closest to what you are currently doing the Regular expression syntax is described here Basics of RegEx

the pattern [0-9.]+ should match an decimal number but be warned it will also match anything that inclues numbers and dots such as ip addresses so if you have a regex of

Regex rx = new Regex(@"([0-9.]+) mm")
<your string> = rx.Replace(<Your string>, @"$1");

the details are :

  • [0-9.] any number or dot

  • + one or more of what ever preceded it

  • () a group that is of special interest

  • $1 the number of the group that you want to replace the match with note $0 is the entire input string

this will replace any string that is (number) mm with just the value of the number

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 F Dev
Solution 2