Search code examples
c#asp.netregexasp.net-mvcmarkup

Regex for Method Calls inside of ASP markup pages by C#


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

Solution

  • 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