tags:

views:

326

answers:

2

This is my string: "This Is {{ dsfdf {{dsfsd}} ewrwrewr }} My Result".

I want to remove the outer curly brackets with their content. The result should be "This Is My Result".

This is my best shot at the moment:

Text = Regex.Replace(Text, "{{([^}]*)}}", String.Empty);

but it doesn't work well. I get "This Is ewrwrewr }} My Text"

Perhaps it should be solved with Balance Matching...

I would be very appreciate if someone could help me solve it, because although many tries I couldn't do it myself.

+1  A: 

What do You think about:

string test = "This Is {{ dsfdf {{dsfsd}} \n jkhhjk ewrwrewr }} My Result";
Console.WriteLine(Regex.Replace(test, "{{.*}}", String.Empty, RegexOptions.Singleline));

Version without "Regex":

string test = "This Is {{ dsfdf {{dsfsd}} \n jkhhjk ewrwrewr }} My Result";
int startIndex = test.IndexOf("{");
int length = test.LastIndexOf("}") - startIndex + 1;
Console.WriteLine(test.Replace(test.Substring(startIndex, length), String.Empty));
mykhaylo
If your real case is as simple as your example, this should be fine!
glenn mcdonald
Wouldn't this also remove stuff across bracket groups? {{ 1 {{ 2 }} 3 }} 4 {{ 5 }} <- removes 4 also?
Tor Valamo
thanks for your quick reply...!it works! but... i didn't mention it before... my mistake.it has multiple lines it. a better example would be:"This Is {{ dsfdf {{dsfsd}} \n jkhhjk ewrwrewr }} My Result"
Tom
@Tom: You can add one more parameter to make this work with new lines: "RegexOptions.Singleline".
Mark Byers
Glenn: Tom presented an example for which I gave the simplest solution(as for me). My solution doesn't handle all possible cases ;).
mykhaylo
And by "work", I mean that it will eat the entire scetion from the first {{ to the last }}, which might not be what you want.
Mark Byers
+2  A: 

A simple but slow way is to apply the regex multiple times until there are no more changes:

using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main(string[] args)
    {
        string s = "This Is {{ dsfdf {{dsfsd}} ewrwrewr }} My Result";

        Regex regex = new Regex("{{({?}?[^{}])*}}");
        int length;
        do
        {
            length = s.Length;
            s = regex.Replace(s, "");
        } while (s.Length != length);

        Console.WriteLine(s);
     }
}
Mark Byers
This way is more powerful, and handles multiple levels of nesting...
glenn mcdonald
this one works great! thank you for your fast answer...i didn't know what a geniuses are hanging around here :))
Tom