Home > database >  In C# string how to replace two chararacters ignoring a number
In C# string how to replace two chararacters ignoring a number

Time:02-11

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"

CodePudding user response:

If your JSON is coming in with two different formats, rather than trying to hack the JSON string into something usable, it is much safer to use a custom JsonConverter. For example:

public class MillimetreJsonConverter : JsonConverter<double>
{
    public override double Read(ref Utf8JsonReader reader, Type typeToConvert, 
        JsonSerializerOptions options)
    {
        // First try to get a double, if it works then simply return it
        if(reader.TryGetDouble(out var val))
        {
            return val;
        }
        
        // Otherwise we get the string value e.g. "0.2 mm" and
        // do some simple string manipulation on it
        var value = reader.GetString()!;
        value = value.Replace(" mm", "");
        
        if(double.TryParse(value, out var result))
        {
            return result;
        }

        // If we get here, perhaps we should throw an exception?
        return 0;
    }

    public override void Write(Utf8JsonWriter writer, double value, 
        JsonSerializerOptions options)
    {
        // You can fill this in if you need it
        throw new NotImplementedException();
    }
}

Now you can modify the class to deserialise into, assuming your JSON looks like this {"myVar": "0.2 mm"},:

public class Foo
{
    [JsonConverter(typeof(MillimetreJsonConverter))]
    public double myVar { get; set; }
}

Finally, it's simple to deserialise:

var foo = JsonSerializer.Deserialize<Foo>(json);

CodePudding user response:

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.

CodePudding user response:

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

  • Related