如何在c#中替换两个字符之间的文本

use*_*724 8 .net c# regex replace

我有点困惑写正则表达式找到两个分隔符之间的文本{}并用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();
Run Code Online (Sandbox Code Playgroud)

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

Kam*_*ski 9

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

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


Sud*_*udi 8

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");
Run Code Online (Sandbox Code Playgroud)


chr*_*dam 6

要获取要替换的括号之间的字符串,请使用 Regex 模式

    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'  
Run Code Online (Sandbox Code Playgroud)

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

string correctString = errString.Replace(toReplace, "document");
Run Code Online (Sandbox Code Playgroud)

正则表达式模式的解释:

\{                 # 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"
Run Code Online (Sandbox Code Playgroud)

  • 添加对所用正则表达式模式的解释大大增加了答案,因为人们通常看这样的问题不会有太多使用正则表达式 +1 的知识 (2认同)

Med*_*noc 1

您需要两次调用Substring(),而不是一次:一次调用 get textBefore,另一个调用 get 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;
Run Code Online (Sandbox Code Playgroud)

如果您想保留牙套,则需要进行一些小的调整:

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;
Run Code Online (Sandbox Code Playgroud)