RegEx for LINQ like syntax
I have a string in the format:
MyList.Where(abc).GroupBy(def).Sum(ghi)
The Where & GroupBy parts are optional as is the argument to the function, so.
ThisList.Count
is also valid.
I'm trying to find a RegEx string that will match this and return the values:
The List name (e.g. MyList), the where condition (e.g. abc), the GroupBy attribute (e.g def), the function name (e.g. Sum) and the function attribute (e.g. ghi).Clarification:
The List name is one word abc can be a comp开发者_开发知识库lex expression, but there will be no close brackets which are not in quotation marks def will be a single word ghi will be a single word or a list of words separated by ","(?<list>\w+)\s* ([.]\s*Where\s*[(]\s*(?<wherearg>.*?)\s*[)]\s*)? ([.]\s*GroupBy\s*[(]\s*(?<groupbyarg>.*?)\s*[)]\s*)? [.]\s*(?<func>\w+)\s*[(]\s*(?<funcarg>.*?)\s*[)]
You can use a regex to validate the syntax, like:
^[A-Za-z]+(\.[A-Za-z]+\([A-Za-z]+\))*(\.[A-Za-z]+)?
but this will result in a valid or invalid decision.
I am not sure if you really want to grep the method names and values at the same time. That would limit your syntax: for instance all methods (GroupBy, Where) have to be in the right order. Maybe it is easier to split the string by .
and extract the parts you need one by one.
Assuming where/groupby/function parameters to be words, you can use:
^(\w+)(?:\.Where\((\w+)\))?(?:\.GroupBy\((\w+)\))?\.(\w+)(?:\((\w+)\))?$
- Group 1 would have the list name
- Group 2 would have the where condition or null
- Group 3 would have the group by condition or null
- Group 4 would have the function
- Group 5 would have the function parameter or null
If they're going to be complex C# expressions, the corresponding regex will be quite complex that you'll hate yourself tomorrow for choosing regex for this.
This gives you the expected result.
^(?<List>[^\.]\*)|\.(?<Op>[^\(\.]*)\(*(?<Param>[^\)\.]*)
精彩评论