Match and replace

后端 未结 5 2065
有刺的猬
有刺的猬 2020-12-08 14:03

I have a long string and within that string I have the following text:

\"formatter\": \"SomeInformationHere\"

I need to fi

相关标签:
5条回答
  • 2020-12-08 14:50

    You can use the Regex.Replace method like this:

    string pattern = "\"formatter\": \"(.*)\"";
    myString = Regex.Replace(myString, pattern, "\"formatter\": $1");
    
    0 讨论(0)
  • 2020-12-08 14:53

    Most probably "the replacement seems to work as if the "singleline" option has been selected" beacause the initially used by you regex will match correctly up to the 14th symbol in

    **"formatter": "SomeInformationHere"**
    

    , but after that it will match every symbol nomatter what it is, including the next fist occurance of double quotes, and it will continue untill the first new line. That's how .* expression works because of it's greedness (Check greedy vs lazy regex). So I suppose that you have only to modify

    "\"formatter\": ([\"]).*([\"])"
    

    to

    "\"formatter\": ([\"]).*?([\"])"
    
    0 讨论(0)
  • 2020-12-08 14:57

    Use this:

    string longString = @"""formatter"": ""SomeInformationHere""";
    string pattern = "(\"formatter\": )([\"])(.*)([\"])";
    string result = Regex.Replace(longString, pattern, "$1$3");
    

    This replaces all found matches with the second and the fourth sub group of the match. The complete match is the first sub group ($0) and all parts in parenthesis create a new sub group.

    0 讨论(0)
  • 2020-12-08 15:03
    var pattern = @"^(\s*""formatter""\s*:\s*)[""](.*)[""](\s)*$";
    var regex = new Regex(pattern, RegexOptions.Compiled | RegexOptions.Multiline);
    myString = regex.Replace(myString, "$1$2$3");
    
    0 讨论(0)
  • 2020-12-08 15:06

    Everybody else has pretty much nailed it with using capturing groups and substitutions, just wanted to provide a little more context:

    The main two things that are used here are Named Capturing Groups and Substitutions

    static void Main(string[] args) {
    
        var input = new[] {
            "\"formatter\": \"John\"", 
            "\"formatter\": \"Sue\"", 
            "\"formatter\": \"Greg\""
        };
    
        foreach (var s in input) {
            System.Console.Write("Original: [{0}]{1}", s, Environment.NewLine);
            System.Console.Write("Replaced: [{0}]{1}", ReFormat(s), Environment.NewLine);
            System.Console.WriteLine();
        }
    
        System.Console.ReadKey();
    }
    
    private static String ReFormat(String str) {
        //Use named capturing groups to make life easier
        var pattern = "(?<label>\"formatter\"): ([\"])(?<tag>.*)([\"])";
    
        //Create a substitution pattern for the Replace method
        var replacePattern = "${label}: ${tag}";
    
        return Regex.Replace(str, pattern, replacePattern, RegexOptions.IgnoreCase);
    }
    
    0 讨论(0)
提交回复
热议问题