【问题标题】:How to replace the text between two characters in c#c#如何替换两个字符之间的文本
【发布时间】:2013-12-20 10:45:01
【问题描述】:

我有点困惑编写正则表达式来查找两个分隔符之间的文本 { } 并将文本替换为 c# 中的另一个文本,如何替换?

我试过了。

        StreamReader sr = new StreamReader(@"C:abc.txt");
        string line;
        line = sr.ReadLine();

        while (line != null)
        {

            if (line.StartsWith("<"))
            {
                if (line.IndexOf('{') == 29)
                {
                    string s = line;
                    int start = s.IndexOf("{");
                    int end = s.IndexOf("}");
                    string result = s.Substring(start+1, end - start - 1);

                }
            }
            //write the lie to console window
            Console.Write Line(line);
            //Read the next line
            line = sr.ReadLine();
        }
        //close the file
        sr.Close();
        Console.ReadLine();

我想用另一个文本替换找到的文本(结果)。

【问题讨论】:

    标签: c# .net regex replace


    【解决方案1】:

    使用带有模式的正则表达式:\{([^\}]+)\}

    Regex yourRegex = new Regex(@"\{([^\}]+)\}");
    string result = yourRegex.Replace(yourString, "anyReplacement");
    

    【讨论】:

    • +1,虽然我认为你可以在不转义字符类中的} 的情况下逃脱。
    【解决方案2】:
    string s = "data{value here} data";
    int start = s.IndexOf("{");
    int end = s.IndexOf("}", start);
    string result = s.Substring(start+1, end - start - 1);
    s = s.Replace(result, "your replacement value");
    

    【讨论】:

    • 感谢您的回复。
    • 我认为这是最简单的答案。我认为您不需要从结果的第二个参数开始。你只需要 (end - 1)
    • 下面的代码在我的情况下更合适,因为它不仅考虑了 1 个字符。当我们使用上述引号类型时,我们建议我们可以使用更长的文本 - 字符串而不是字符。 int start = text.IndexOf("Text between this...") + start.Length; int end = text.IndexOf("...and this"); string oldValueToBeReplaced = text.Substring(start, end - start); s = s.Replace(oldValueToBeReplaced , "your replacement value");
    【解决方案3】:

    要替换括号之间的字符串,请使用正则表达式模式

        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'  
    

    要替换找到的文本,您可以简单地使用 Replace 方法,如下所示:

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

    正则表达式模式的解释:

    \{                 # 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"
    

    【讨论】:

    • 添加对所使用的正则表达式模式的解释大大增加了答案,因为通常看这样的问题的人不会对使用正则表达式+1有太多了解
    【解决方案4】:

    以下正则表达式将匹配您指定的条件:

    string pattern = @"^(\<.{27})(\{[^}]*\})(.*)";
    

    以下将执行替换:

    string result = Regex.Replace(input, pattern, "$1 REPLACE $3");
    

    对于输入:"&lt;012345678901234567890123456{sdfsdfsdf}sadfsdf" 这给出了输出 "&lt;012345678901234567890123456 REPLACE sadfsdf"

    【讨论】:

      【解决方案5】:

      您需要两次调用Substring(),而不是一次:一次获取textBefore,另一次获取textAfter,然后将它们与您的替换连接起来。

      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;
      

      如果你想保留牙套,你需要做一个小调整:

      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;
      

      【讨论】:

        【解决方案6】:

        如果你想避免任何正则表达式,最简单的方法是使用 split 方法。这是一种方法:

        string s = "sometext {getthis}";
        string result= s.Split(new char[] { '{', '}' })[1];
        

        【讨论】:

        • 只有当你知道{}之间的文本会落入哪个位置时才会起作用。
        【解决方案7】:

        您可以使用其他人已经发布的正则表达式,或者您可以使用更高级的正则表达式,它使用平衡组来确保开始 { 与结束 } 平衡。

        那个表达式就是(?&lt;BRACE&gt;\{)([^\}]*)(?&lt;-BRACE&gt;\})

        你可以在RegexHero在线测试这个表达式。

        您只需将输入字符串与此正则表达式模式匹配,然后使用正则表达式的替换方法,例如:

        var result = Regex.Replace(input, "(?<BRACE>\{)([^\}]*)(?<-BRACE>\})", textToReplaceWith);
        

        有关更多 C# 正则表达式替换示例,请参阅http://www.dotnetperls.com/regex-replace

        【讨论】:

        • 虽然我很喜欢平衡组,但这里真的需要它们吗?如果缺少任何一个大括号,标准匹配无论如何都会失败。
        猜你喜欢
        • 2020-08-15
        • 1970-01-01
        • 2020-06-26
        • 2015-08-26
        • 2021-07-23
        • 2019-12-25
        • 2013-08-07
        • 1970-01-01
        • 2021-01-28
        相关资源
        最近更新 更多