How to replace the text between two characters in c#

前端 未结 7 2118
醉梦人生
醉梦人生 2020-12-06 06:24

I am bit confused writing the regex for finding the Text between the two delimiters { } and replace the text with another text in c#,how to replace?

7条回答
  •  独厮守ぢ
    2020-12-06 06:59

    To get the string between the parentheses to be replaced, use the Regex pattern

        string errString = "This {match here} uses 3 other {match here} to {match here} the {match here}ation";
        string toReplace =  Regex.Match(errString, @"\{([^\}]+)\}").Groups[1].Value;    
        Console.WriteLine(toReplace); // prints 'match here'  
    

    To then replace the text found you can simply use the Replace method as follows:

    string correctString = errString.Replace(toReplace, "document");
    

    Explanation of the Regex pattern:

    \{                 # Escaped curly parentheses, means "starts with a '{' character"
            (          # Parentheses in a regex mean "put (capture) the stuff 
                       #     in between into the Groups array" 
               [^}]    # Any character that is not a '}' character
               *       # Zero or more occurrences of the aforementioned "non '}' char"
            )          # Close the capturing group
    \}                 # "Ends with a '}' character"
    

提交回复
热议问题