字符串操作以提取特定模式的子字符串

时间:2013-08-30 10:54:31

标签: c#

我在c#

中有以下字符串
Count([AssignedTo]) as [AssignedTo] , Sum([Billing Amount]) as [Billing Amount] , Max([Billing Rate]) as [Billing Rate] , Min([ExecutionDate]) as [ExecutionDate] , Average([HoursSpent]) as [HoursSpent] , [Project], [Sub-Project], [TaskName], [Vendor], [Work Classification], [Work Done], Count([WorkItemType]) as [WorkItemType]  

现在我想要通过字符串操作或linq

列出具有聚合函数的所有字段

输出

Count([AssignedTo])

 Sum([Billing Amount])

 Max([Billing Rate])

 Min([ExecutionDate])

 Average([HoursSpent]) 

Count([WorkItemType])

3 个答案:

答案 0 :(得分:2)

也许这适合你:

var aggr = new []{ "Count", "Sum", "Max", "Min", "Average"};
var allAggregates = text.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
    .Select(col => new{ col, token = col.TrimStart().Split().First() })
    .Where(x => x.token.Contains('(') && aggr.Any(a => x.token.StartsWith(a, StringComparison.OrdinalIgnoreCase)))
    .Select(x => x.token);

DEMO

  

我可以获得仅在函数内部的字段名称

如果可能的话,我更喜欢字符串方法而不是正则表达式:

var allAggregates = text.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
    .Select(col => new { col, token = col.TrimStart().Split().First() })
    .Where(x => x.token.Contains('(') && aggr.Any(a => x.token.StartsWith(a, StringComparison.OrdinalIgnoreCase)))
    .Select(x => {
        string innerPart = x.token.Substring(x.token.IndexOf('(') + 1);
        int index = innerPart.IndexOf(')');
        if (index >= 0)
            innerPart = innerPart.Remove(index);
        return innerPart;
    });

答案 1 :(得分:0)

var aggregates = new []{ "Count", "Sum", "Max", "Min", "Average"};
var output=Regex.Matches(input,@"(\w+)\(.*?\)")
                .Cast<Match>()
                .Where(x=>aggregates.Any(y=>y==x.Groups[1].Value))
                .Select(z=>z.Value);

答案 2 :(得分:0)

这是另一种方式:

string[] funcNames =  new string[]{"Sum","Average","Count","Max","Min"};
string s = "Your String";

var output = from v in s.Split(',')  
             where funcNames.Contains(v.Split('(')[0].Trim())
             select v.Split(new string[]{" as "},  
                            StringSplitOptions.RemoveEmptyEntries)[0].Trim();
             .Split('(')[1].Split(')')[0]; //this line is to get only field names

//Print results
foreach(var str in output) Console.WriteLine(str);