user556396
user556396

Reputation: 597

Best way to find functions with regex?

Hey guys I'm working with a custom scripting language and I am making a sort of IDE for this language in C#. In this language the functions are defined like this:

yourfunctionhere(possiblepararmhere)
{
  yourcodehere;
}

I've been trying to figure out the best way to get a list of all the functions via regex and couldn't find a working way to get a list of all the defined functions. Could somebody tell me of a better way or a way to do it with regex? Thanks a lot!

EDIT: Would something like this work in C#? %[a-z_0-9^[^]*]++ [a-z_0-9*^[^]]+[ ^t]++[a-z_0-9*^[^]]+[ ^t]++^([*a-z_0-9]+^)[ ^t]++([^p*&, ^t^[^]a-z_0-9./(!]++)[~;]

Upvotes: 2

Views: 3726

Answers (3)

Aniruddha Poorna
Aniruddha Poorna

Reputation: 19

var pat=  @"\b(public|private|internal|protected)\s*" + @"\b(static|virtual|abstract)?\s*[a-zA-Z_]*(?<method>\s[a-zA-Z_]+\s*)" + @"\((([a-zA-Z_\[\]\<\>]*\s*[a-zA-Z_]*\s*)[,]?\s*)+\)" ;

Upvotes: -1

Kevin Cathcart
Kevin Cathcart

Reputation: 10098

If you just want a list of function names something like this might work:

Regex.Matches(source,@"([a-zA-Z0-9]*)\s*\([^()]*\)\s*{").Cast<Match>()
    .Select (m => m.Groups[1].Captures[0].Value).ToArray()

Basically, that regex is looking for any group of alphanumeric characters, followed by optional white space, followed an open parenthesis, followed by zero or more non-parentheses, followed by a close parenthesis, followed by optional white space, and then an open curly brace.

Then from there you extract just the beginning portion, and create a list. Assuming the language does not otherwise allow a close parenthesis to be followed by an open curly bracket, then the above should work. Otherwise more details would be needed.

Upvotes: 3

Petar Ivanov
Petar Ivanov

Reputation: 93000

It'd be much easier if you changed your syntax by adding a reserved keyword like 'def', so your declarations become:

def yourfunctionhere(possiblepararmhere)
{
    yourcodehere;
}

Then you can use a simple regex like def [a-zA-Z0-9]+.

Upvotes: 0

Related Questions