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

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

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

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

 Regex yourRegex = new Regex(@"\{([^\}]+)\}"); string result = yourRegex.Replace(yourString, "anyReplacement"); 
 string s = "data{value here} data"; int start = s.IndexOf("{"); int end = s.IndexOf("}"); string result = s.Substring(start+1, end - start - 1); s = s.Replace(result, "your replacement value"); 

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

  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" 

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

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

以下将执行替换:

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

输入: "<012345678901234567890123456{sdfsdfsdf}sadfsdf"这给出了输出"<012345678901234567890123456 REPLACE sadfsdf"

你需要两次调用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; 

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

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

您可以使用其他人已经发布的Regex表达式,或者您可以使用更高级的Regex使用平衡组来确保开口{由关闭平衡}。

那个表达式是(?\{)([^\}]*)(?<-BRACE>\})

您可以在RegexHero在线测试此表达式。

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

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

有关更多C#Regex替换示例,请访问http://www.dotnetperls.com/regex-replace 。

您可以使用许多function来执行此操作。

String.Replace(“查找字符”,“替换为”);

或String.SubString();