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

C# 如何替换c中两个字符之间的文本#,c#,.net,regex,replace,C#,.net,Regex,Replace,我在编写正则表达式时有点困惑,因为它在两个分隔符{}之间查找文本,并用c#中的另一个文本替换文本,如何替换 我试过这个 StreamReader sr = new StreamReader(@"C:abc.txt"); string line; line = sr.ReadLine(); while (line != null) { if (line.StartsWith("<"))

我在编写正则表达式时有点困惑,因为它在两个分隔符{}之间查找文本,并用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();
StreamReader sr=newstreamreader(@“C:abc.txt”);
弦线;
line=sr.ReadLine();
while(行!=null)
{

if(line.StartsWith(“您需要两个调用
Substring()
,而不是一个调用:一个调用在
之前获取
文本,另一个调用在
之后获取
文本,然后将它们与替换项连接起来

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];

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

    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'  
然后,要替换找到的文本,只需使用以下替换方法:

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"

您可以使用其他人已经发布的正则表达式,也可以使用更高级的正则表达式,该正则表达式使用平衡组来确保开头{被结尾}平衡

这个表达式就是
(?\{)([^\}]*)(?\})

您可以在上在线测试此表达式

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

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

有关C#Regex Replace示例的更多信息,请参阅。

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

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

对于输入:
“感谢您的回复。我认为这是最简单的答案。不过,我认为您不需要从结果的第二个参数开始。您只需要(end-1)下面的代码在我的情况下更合适,因为它不仅考虑了1个字符。当我们使用上面的引号类型时,我们建议可以使用更长的文本-字符串而不是字符。int start=text.IndexOf(“此之间的文本…”)+start.Length;int end=text.IndexOf(“…和此”);字符串OldValueToBereplace=text.Substring(开始,结束-开始);s=s.Replace(OldValueToBereplace,“您的替换值”)
+1,尽管我认为你可以不逃过字符类中的
}
而逃脱。虽然我非常喜欢平衡组,但这里真的需要它们吗?如果缺少任何一个大括号,标准匹配都会失败。添加对所用正则表达式模式的解释会大大增加答案,因为人们会看到以下问题:e这通常不会有太多关于使用regex+1的知识,只有当您知道
{}
之间的文本将位于哪个位置时,它才会起作用。
var result = Regex.Replace(input, "(?<BRACE>\{)([^\}]*)(?<-BRACE>\})", textToReplaceWith);
string pattern = @"^(\<.{27})(\{[^}]*\})(.*)";
string result = Regex.Replace(input, pattern, "$1 REPLACE $3");