Using Regex.Replace to keep characters that can be vary

后端 未结 3 1833
不知归路
不知归路 2021-01-06 12:29

I have the following:

string text = \"version=\\\"1,0\\\"\";

I want to replace the comma for a dot, while keeping

相关标签:
3条回答
  • 2021-01-06 12:50

    You can perhaps use capture groups to keep the numbers in front and after for replacement afterwards for a more 'traditional way' to do it:

    string text = "version=\"1,0\"";
    var regex = new Regex(@"version=""(\d*),(\d*)""");
    var result = regex.Replace(text, "version=\"$1.$2\"");
    

    Using parens like the above in a regex is to create a capture group (so the matched part can be accessed later when needed) so that in the above, the digits before and after the comma will be stored in $1 and $2 respectively.


    But I decided to delve a little bit further and let's consider the case if there are more than one comma to replace in the version, i.e. if the text was version="1,1,0". It would actually be tedious to do the above, and you would have to make one replace for each 'type' of version. So here's one solution that is sometimes called a callback in other languages (not a C# dev, but I fiddled around lambda functions and it seems to work :)):

    private static string SpecialReplace(string text)
    {
        var result = text.Replace(',', '.');
        return result;
    }
    public static void Main()
    {
        string text = "version=\"1,0,0\"";
        var regex = new Regex(@"version=""[\d,]*""");
        var result = regex.Replace(text, x => SpecialReplace(x.Value));
        Console.WriteLine(result);
    }
    

    The above gives version="1.0.0".

    "version=""[\d,]*""" will first match any sequence of digits and commas within version="...", then pass it to the next line for the replace.

    The replace takes the matched text, passes it to the lambda function which takes it to the function SpecialReplace, where a simple text replace is carried out only on the matched part.

    ideone demo

    0 讨论(0)
  • 2021-01-06 13:00

    You need a regex like this to locate the comma

    Regex reg = new Regex("(version=\"[0-9]),([0-9]\")");
    

    Then do the repacement:

    text = reg.Replace(text, "$1.$2");
    

    You can use $1, $2, etc. to refer to the matching groups in order.

    0 讨论(0)
  • 2021-01-06 13:02
    (?<=version=")(\d+),
    

    You can try this.See demo.Replace by $1.

    https://regex101.com/r/sJ9gM7/52

    0 讨论(0)
提交回复
热议问题