I want to match (select from class file) methodsname, properties name and fields name.
This is example class:
class Perl
{
string _name;
public string Name { get; set; }
public Perl()
{
// Assign this._name
this._name = "Perl";
// Assign _name
_name = "Sam";
// The two forms reference the same field.
Console.WriteLine(this._name);
Console.WriteLine(_name);
}
public static string doSomething(string test)
{
bla test;
}
}
I got code for the methods:
(?:public|private|protected)([\s\w]*)\s+(\w+)\s*\(\s*(?:\w+\s+(\w+)\s*,?\s*)+\)
And i got questions:
- this above regex code gets all methods and it works pretty well but also i want it to select method name but without parameters and accessors. So from exaplmce class using my code result will be: public Perl() and public static doSomething(string test) but i want that kind of result: Perl() and doSomething(). So - my code matches good but i want result to be displayed just like I wrote in previous sentence.
- how to select properties ? with result displayed: type and property name. So from exaple class result will be: string Name
- how to select fields with result: type field_name. In out case it will be: string _name
Use this
Regex
for methods
and get groups named
methodName
andparameterType
andparameter
.and for fields:
and get groups named
type
andname
.for example your code for methods can be like this:
You can use Irony - .NET Language Implementation Kit from codeplex too.
I suggest looking at
Microsoft.VisualStudio.CSharp.Services.Language
namespace and other Visual Studio Extensibility functionality. This would eliminate the need to compile.A language such as C# accepts too many variations in statements syntax to be parsed using regular expressions only. On top of regexes, you need a contextual grammar parser.
I would give Roslyn a try: It's a C# compiler whose internals are accessible from your code. Ask Roslyn to parse the code and query it about whatever info you need.
As stated in comments to your answer, much more reliable method is to compile your .cs files and then use reflection to interrogate types for members you are interested in. It will involve the following:
Process
class.EDIT: As an alternative to csc.exe, you could use CodeDOM - there is an example that contains all you need.