How to replace the text between two characters in c#

34,708

Solution 1

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

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

Solution 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");

Solution 3

To get the string between the parentheses to be replaced, use the Regex pattern

    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'  

To then replace the text found you can simply use the Replace method as follows:

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

Explanation of the Regex pattern:

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

Solution 4

The following regular expression will match the criteria you specified:

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

The following would perform a replace:

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

For the input: "<012345678901234567890123456{sdfsdfsdf}sadfsdf" this gives the output "<012345678901234567890123456 REPLACE sadfsdf"

Solution 5

You need two calls to Substring(), rather than one: One to get textBefore, the other to get textAfter, and then you concatenate those with your replacement.

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;

If you want to keep the braces, you need a small adjustment:

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;
Share:
34,708
user2477724
Author by

user2477724

Updated on August 26, 2020

Comments

  • user2477724
    user2477724 over 3 years

    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.

  • user2477724
    user2477724 over 10 years
    Thanks for giving reply.
  • Rawling
    Rawling over 10 years
    +1, although I think you can get away without escaping the } inside the character class.
  • Rawling
    Rawling over 10 years
    Much as I love balancing groups, are they really needed here? If either brace is missing, a standard match will fail anyway.
  • Yusha
    Yusha about 7 years
    I think this is the most simplest answer. I don't think you need start in your second parameter of result though. you just need (end - 1)
  • Kevin
    Kevin almost 7 years
    adding in the explanation of the regex pattern used greatly adds to the answer since people looking at questions like this in general won't have much knowledge of using regex +1
  • Mateusz Sęczkowski
    Mateusz Sęczkowski almost 5 years
    Code below was in my case more suitable as it takes into consideration not only 1 character. When we use the type of quotation marks as above we suggest that we can use longer text - string instead of a character. 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");
  • diegosasw
    diegosasw almost 3 years
    That would only work when you know which position will the text between {} fall into.