Attention: We are retiring the ASP.NET Community Blogs. Learn more >

Neat, but probably inefficient example of conditional

Started messing around with conditional matching today and was rather proud of myself when I got this stuff to work.

The pattern matches compound statements in the body of a simple if statement taking into account that there may or may not be braces.

I'll bet a MILLION bucks that there's a *much* more efficient way to do this, but that's for another lesson ;-)


using System ;
using System.Text.RegularExpressions ;

namespace RegexSnippets.Tests
{
    public class Foo
    {
        public static void Main()
        {
          /*
            TRY WITH THIS AS WELL...
            string source = @"if( 1 == 1 ){ 
                            MessageBox.Show( ""this is in the compound statement block."" ) ;
                       } 
                       MessageBox.Show( ""this is not."" ) ;
                    aaa ;" ;
            */
      
            string source = @"if( 1 == 1 ){ 
                            MessageBox.Show( ""this is in the compound statement block."" ) ;
                            MessageBox.Show( ""so is this."" ) ;
                    }
                    aaa ;" ;
            

            string pattern = @"(?'statementType'\w+)\s*?
                        \((?'condition'.*?)\)(?:\s*)?
                            (?'openingCompound'\{)?(?:\s*)?
                            (?(openingCompound)
                                (?'compoundStatements'.*?
                                    (?'closingCompound'})
                                )
                                |
                                (?'compoundStatements'.*?
                                    (?'closingCompound';)
                                )
                            )
                        (?'theRest'.*)" ;

            Regex re = new Regex( 
                    pattern, 
                    RegexOptions.IgnoreCase
|RegexOptions.Multiline
|RegexOptions.IgnorePatternWhitespace
|RegexOptions.Singleline ) ; Match m = re.Match( source ) ;
if( m.Groups["condition"].Success ) { Console.WriteLine("Statement Type: {0}", m.Groups["statementType"]) ; Console.WriteLine("Condition: {0}", m.Groups["condition"]) ; Console.WriteLine("Opening Compound: {0}", m.Groups["openingCompound"].Success) ; Console.WriteLine("Compound Statements: {0}", m.Groups["compoundStatements"].Value.Trim()) ; Console.WriteLine("Closing Compound Char: {0}", m.Groups["closingCompound"].Value.Trim()) ; Console.WriteLine("The rest: {0}", m.Groups["theRest"].Value.Trim()) ; } else { Console.WriteLine("Parser Error!") ; } Console.ReadLine() ; } } }

1 Comment

Comments have been disabled for this content.