How to replace the text between two characters in c#

前端 未结 7 2013
醉梦人生
醉梦人生 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 07:14

    You need two calls to Substring(), rather than one: One to get textBefore, the other to get textAfter, and then you concatenate those with your replacement.

    int start = s.IndexOf("{");
    int end = s.IndexOf("}");
    //I skip the check that end is valid too avoid clutter
    string textBefore = s.Substring(0, start);
    string textAfter = s.Substring(end+1);
    string replacedText = textBefore + newText + textAfter;
    

    If you want to keep the braces, you need a small adjustment:

    int start = s.IndexOf("{");
    int end = s.IndexOf("}");
    string textBefore = s.Substring(0, start-1);
    string textAfter = s.Substring(end);
    string replacedText = textBefore + newText + textAfter;
    
    0 讨论(0)
提交回复
热议问题