I'm writing a VSIX extension for Visual Studio. With that plugin a user can select a class file from his solution explorer in VS, (so an actual .cs
file somewhere on disk) and then perform a certain action on that file by triggering my VSIX code through a context menu item.
My VSIX extension needs to know what the public
and internal
properties are of the selected class file.
I'm trying to solve this by using a regex, But I'm kind of stuck with it. I can't figure out how to only get the property names of the class. It finds too much right now.
This is the regex I have so far:
\s*(?:(?:public|internal)\s+)?(?:static\s+)?(?:readonly\s+)?(\w+)\s+(\w+)\s*[^(]
Demo: https://regex101.com/r/ngM5l7/1 From this demo I want to extract all the property names, so:
Brand,
YearModel,
HasRented,
SomeDateTime,
Amount,
Name,
Address
PS. I know that a regex isn't the best for this kind of job. But I think I don't have any other options from a VSIX extension.
how to only get the property names of the class.
This pattern is commented, so use IgnorePatternWhiteSpace
as an option or remove all comments and join onto one line.
But this pattern gets all your data as you provided in the example.
(?>public|internal) # find public or internal
\s+ # space(s)
(?!class) # Stop Match if class
((static|readonly)\s)? # option static or readonly and space.
(?<Type>[^\s]+) # Get the type next and put it into the "Type Group"
\s+ # hard space(s)
(?<Name>[^\s]+) # Name found.
(?<Named> ...)
such as mymatch.Groups["Named"].Value
or by the hard integer. My tool (created for myself) reports these matches and the groups :
Match #0
[0]: public string Brand
["Type"] → [1]: string
["Name"] → [2]: Brand
Match #1
[0]: internal string YearModel
["Type"] → [1]: string
["Name"] → [2]: YearModel
Match #2
[0]: public List<User> HasRented
["Type"] → [1]: List<User>
["Name"] → [2]: HasRented
Match #3
[0]: public DateTime? SomeDateTime
["Type"] → [1]: DateTime?
["Name"] → [2]: SomeDateTime
Match #4
[0]: public int Amount;
["Type"] → [1]: int
["Name"] → [2]: Amount;
Match #5
[0]: public static string Name
["Type"] → [1]: string
["Name"] → [2]: Name
Match #6
[0]: public readonly string Address
["Type"] → [1]: string
["Name"] → [2]: Address