11

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.

Liath
  • 9,913
  • 9
  • 51
  • 81
user2477724
  • 141
  • 1
  • 4
  • 10

7 Answers7

13

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

Regex yourRegex = new Regex(@"\{([^\}]+)\}");
string result = yourRegex.Replace(yourString, "anyReplacement");
Valamas
  • 24,169
  • 25
  • 107
  • 177
Kamil Budziewski
  • 22,699
  • 14
  • 85
  • 105
13
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");
DxTx
  • 3,049
  • 3
  • 23
  • 34
Sudhakar Tillapudi
  • 25,935
  • 5
  • 37
  • 67
  • Thanks for giving reply. – user2477724 Dec 20 '13 at 10:58
  • 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) – Yusha Feb 15 '17 at 17:23
  • 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");` – Mateusz Sęczkowski May 28 '19 at 17:19
8

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"
chridam
  • 100,957
  • 23
  • 236
  • 235
  • 2
    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 – Kevin Jul 20 '17 at 09:26
2

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"

samjudson
  • 56,243
  • 7
  • 59
  • 69
1

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;
Medinoc
  • 6,577
  • 20
  • 42
1

You can use the Regex expression that some others have already posted, or you can use a more advanced Regex that uses balancing groups to make sure the opening { is balanced by a closing }.

That expression is then (?<BRACE>\{)([^\}]*)(?<-BRACE>\})

You can test this expression online at RegexHero.

You simply match your input string with this Regex pattern, then use the replace methods of Regex, for instance:

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

For more C# Regex Replace examples, see http://www.dotnetperls.com/regex-replace.

Roy Dictus
  • 32,551
  • 8
  • 60
  • 76
0

the simplest way is to use split method if you want to avoid any regex .. this is an aproach :

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