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();
1
  • Regular expressions aren't the best solution for this, you'll run into issues with nested method calls, eg. Method1(Method2(...)). See this for more about Regex and nested structures. A better way would be to use something like ANTLR Also see this, it's about HTML but should give you the general idea Commented May 6, 2016 at 17:04

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.