Got more questions? Find advice on: ASP | SQL | XML | Windows
in Search
Welcome to RegexAdvice Sign in | Join | Help

Match exactly one set of outer-most curly braces, nesting allowed

Last post 07-02-2009, 1:08 PM by ddrudik. 5 replies.
Sort Posts: Previous Next
  •  07-02-2009, 9:01 AM 54502

    Match exactly one set of outer-most curly braces, nesting allowed

    My regular expression savvy is not up-to-snuff and I'm having trouble getting an expression exactly correct. Any help is greatly appreciated.

    I need an expression that will match strings that contain exactly 1 set of outer-most curly braces. Whatever happens between those braces is legit, including nested braces. So, for example:

    {test} OK
    this is a {test} string OK
    {this} is a {test} FAIL
    {this {is} a test} OK
    this { is {{{ a t}est OK

    I hope that's clear. Thanks!

  •  07-02-2009, 9:30 AM 54504 in reply to 54502

    Re: Match exactly one set of outer-most curly braces, nesting allowed

    What platform?
  •  07-02-2009, 10:19 AM 54505 in reply to 54504

    Re: Match exactly one set of outer-most curly braces, nesting allowed

    .Net
  •  07-02-2009, 11:51 AM 54509 in reply to 54502

    Re: Match exactly one set of outer-most curly braces, nesting allowed

    using System;
    using System.Text.RegularExpressions;
    namespace myapp
    {
        class Class1
        {
            static void Main(string[] args)
            {
                String sourcestring = "this { is {{{ a t}est";
                Regex re = new Regex(@"\{(?>[^{}]+|\{(?<DEPTH>)|\}(?<-DEPTH>))*(?(DEPTH)(?!))\}");
                MatchCollection mc = re.Matches(sourcestring);
                if (mc.Count != 1)
                {
                    Console.WriteLine("Fail!");
                }
                else
                {
                    Console.WriteLine("Pass!");
                }
            }
        }
    }


  •  07-02-2009, 12:56 PM 54519 in reply to 54509

    Re: Match exactly one set of outer-most curly braces, nesting allowed

    Wow, thanks. I guess it wasn't trivial.... Now I need to look up all those patterns being used and figure out what they mean!

    Thanks!

  •  07-02-2009, 1:08 PM 54520 in reply to 54519

    Re: Match exactly one set of outer-most curly braces, nesting allowed

    I would recommend Mastering Regular Expressions by Friedl, that's where I first saw that pattern.


View as RSS news feed in XML