locked
Can we capture if statement with regular expression ?

    Question

  • Hi everybody

    I want to know, Can we capture if statement with regular expression ? as if exists syntax error in our if statement , we declaration it.

    if your answer is YES , How we can do it?
    I want its pattern.

    Thanks to u
    Saturday, May 10, 2008 5:25 AM

Answers

  • sorry for the delay. here is the code, hope it still helps:

     

    Code Snippet

    string s = "if (x==0) {8+; } else { i--; }";

    string output = Regex.Replace(s, "if \\([-a-zA-Z0-9+=;,.&!\"\'\\(\\)//*%// ]*\\) \\{[ ]*[-a-zA-Z0-9+=;&!\"\'\\(\\)//*%// ]*;[ ]*\\}", "1", RegexOptions.Singleline);

    Console.WriteLine(output);

     

     

     

     

     

    Sunday, May 18, 2008 9:15 PM
  • The only problem with trying to match a pattern such as an if block is that there maybe nested curly brace blocks inside (other if statements, using, or just plain old { }, etc.).  You may want to look into the balancing group regex capabilities built into .NET: http://blog.stevenlevithan.com/archives/balancing-groups
    Monday, May 19, 2008 12:55 PM

All replies

  •  M-Dayyan wrote:
    Hi everybody

    I want to know, Can we capture if statemen with regular expression ? as if exists syntax error in our if statement , we declaration it.

    if your answer is YES , How we can do it?
    I want its pattern.

    Thanks to u

    i don't really get what you want. do you want to get a pattern in a text file? please give us a sample of where and how the if pattern will appear.

     

     

    Sunday, May 11, 2008 6:04 PM
  • OK, thanks for your answer.

    I want to detect the IF-ELSE statement with Regex class.

    Do u know how I have to do it ?

     

     

    Sunday, May 11, 2008 10:53 PM
  • Sure, in what language?  C style, VB style?  Should it support curly braces and without?
    Monday, May 12, 2008 1:32 PM
  •  

    In C# , like this :

     

    Code Snippet

    If (sth)

    {

    sth;

    }

     

     

     

    Monday, May 12, 2008 9:07 PM
  • sorry for the delay. here is the code, hope it still helps:

     

    Code Snippet

    string s = "if (x==0) {8+; } else { i--; }";

    string output = Regex.Replace(s, "if \\([-a-zA-Z0-9+=;,.&!\"\'\\(\\)//*%// ]*\\) \\{[ ]*[-a-zA-Z0-9+=;&!\"\'\\(\\)//*%// ]*;[ ]*\\}", "1", RegexOptions.Singleline);

    Console.WriteLine(output);

     

     

     

     

     

    Sunday, May 18, 2008 9:15 PM
  • The only problem with trying to match a pattern such as an if block is that there maybe nested curly brace blocks inside (other if statements, using, or just plain old { }, etc.).  You may want to look into the balancing group regex capabilities built into .NET: http://blog.stevenlevithan.com/archives/balancing-groups
    Monday, May 19, 2008 12:55 PM
  • Thanks guys.
    My problem solved .

    Tuesday, May 20, 2008 11:26 AM