Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace the text between two characters in c#

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?

I tried this.

        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();

I want replace the found text(result) with another text.

like image 547
user2477724 Avatar asked Dec 20 '13 10:12

user2477724


1 Answers

Use Regex with pattern: \{([^\}]+)\}

Regex yourRegex = new Regex(@"\{([^\}]+)\}");
string result = yourRegex.Replace(yourString, "anyReplacement");
like image 61
Kamil Budziewski Avatar answered Oct 15 '22 23:10

Kamil Budziewski