Reputation: 89
I have a program where I have to check if any automatic property types matches a class name.
So, for example, if I have:
public class User
{
//Some code here
}
public class Cars
{
public string Brand {get; set;}
public string YearModel {get; set;}
public List<User> HasRented {get; set;}
}
Now, I already have the code to match class names, so I can get the name "User" from "public class User". Problem is, I need the regex to get "List<User>
" from "public List<User> HasRented {get; set;}
". Of course, I want to get all the property types. So I also want the two "string" to match on the regex.
If it is to any help, I've already got a regex that gets the Name of properties, so maybe someone could help me modify it to get the type of properties instead?
REGEX: \w+(?=\s*{\s*get\b)
EDIT: Forgot to mention that I have the source as a string, which is why I would like to match it with regex. To be extra clear: The ONLY thing that I need help with is the regex to get property types from a text that contains a class filled with automatic properties. Not the matching with the class name.
Upvotes: 1
Views: 2491
Reputation: 5395
You can get both name and type with:
(?<type>[^\s]+)\s(?<name>[^\s]+)(?=\s\{get;)
DEMO or just type with:
(\S+(?:<.+?>)?)(?=\s\w+\s\{get;)
Upvotes: 1
Reputation: 7187
Using regular expressions to parse code is no use since the type of properties is not limited to 1 level generics and can be anything like
List<SortedList<string, User>>
in this case, it is better to let the C# compiler (csc) to do the work.
I assume that the code can be compiled of course, since your source code is missing the required using statement for System.Collections.Generic;
Here is the code to compile the source code:
CSharpCodeProvider prov = new CSharpCodeProvider();
CompilerResults results = prov.CompileAssemblyFromFile(new System.CodeDom.Compiler.CompilerParameters(), new string[] { "c:\\temp\\code.txt" });
if (results.Errors.Count == 0)
{
Assembly assembly = results.CompiledAssembly;
foreach (Type type in assembly.GetTypes())
{
Console.WriteLine("Type: {0}", type.Name);
foreach (PropertyInfo pi in type.GetProperties())
{
Console.WriteLine(" Property: {0}, Return Type: {1}", pi.Name, pi.PropertyType);
}
}
}
And here is the output:
Type: User
Type: Cars
Property: Brand, Return Type: System.String
Property: YearModel, Return Type: System.String
Property: HasRented, Return Type: System.Collections.Generic.List`1[User]
Upvotes: 2
Reputation: 16055
regex ^\s*public\s+([^\s]+)\s+[^\s]+\s+\{[^\}\n]+\}
with modifiers global and multiline will return the class names of the properties
Upvotes: 0