0

I need a regex pattern to find any kind of method calls in both Asp Markup pages (webform .aspx) and (MVC cshtml) by c#.

I am looking for a pattern to cover almost possibilities like these:

1)     MethodName1()

2)     ClassName.MethodName2(prm1,prm2,...)

3)     new ClassName.Obj1.Obj2.Method3(...)

4)    [new] [AnyThing].[anthing].[anything]([anything])

5)     MethodName1().ToString() 
 ....

here is my code, the content of file is markup text file.

 int counter = 0;
 string line;
 var regex = new Regex(@"*[a-zA-Z].{1}+*[a-zA-Z](+*[a-zA-Z])+"); //??????

 // Read the asp markup file and parse it line by line.
 var file = new System.IO.StreamReader(path);
 while ((line = file.ReadLine()) != null)
    {                    
      var match = regex.Match(line);
      if (match.Success)
         {
            //Do sth
         }
      counter++;
    }
 file.Close();
Harry Sarshogh
  • 2,137
  • 3
  • 25
  • 48
  • Regular expressions aren't the best solution for this, you'll run into issues with nested method calls, eg. `Method1(Method2(...))`. See [this](http://stackoverflow.com/questions/133601/can-regular-expressions-be-used-to-match-nested-patterns) for more about Regex and nested structures. A better way would be to use something like [ANTLR](http://www.antlr.org/) Also see [this](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454), it's about HTML but should give you the general idea – amura.cxg May 06 '16 at 17:04

1 Answers1

2

try this regular expression, it also adds some named groups of the form(?<groupname>regex), accessed like: myMatch.Groups["myGroupName"].Value:

(?:\[?new]?)?\s*(?<source>(?:\[?\w+\]?\.)*)\[?(?<method>\w+)\]?\((?<args>\[?.*?\]?)\)

input/output: (online demo here)

enter image description here enter image description here

Scott Weaver
  • 7,192
  • 2
  • 31
  • 43