开发者

regex for removing curly brackets with nested curly brackets

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 s开发者_JAVA技巧olved 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.


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜