我想使用.net Regex.Split
方法将此输入string
拆分为array
。它必须对这个词进行分组。
输入:**AAA**-1111,**AAA**-666,**SMT**-QWQE,**SMT**-TTTR
预期产出:
**AAA** : 1111,666
**SMT** : QWQE,TTTR
我需要使用哪种模式?
答案 0 :(得分:2)
正如对问题的评论所指出的那样,你不能一步到位(正则表达式或非正则表达式)。
所以:
类似的东西:
var result = select outer in input.Split(",")
let p = outer.Split('-') // will be string[2]
select new { identifier = p[0], value = p[1] }
into pair
group by pair.identifier into g
select new {
identifier = g.Key
values = String.Join(",", g)
}
答案 1 :(得分:0)
这应该为您提供一个IEnumerable,其中包含key
字符串和字符串列表(以逗号分隔)values
每个字符串:
var input = "AAA-1111,AAA-666,SMT-QWQE,SMT-TTTR";
var list = input.Split(',')
.Select(pair => pair.Split('-'))
.GroupBy(pair => pair.First())
.Select(grp =>
new{
key = grp.Key,
items = String.Join(",", grp.Select(x => x[1]))
});
然后你可以像这样使用它(如果你只想输出值):
string output = "";
foreach(var grp in list)
{
output += grp.key + ": " + grp.items + Environment.NewLine;
}
答案 2 :(得分:0)
FWIW这里使用流利语法的相同解决方案,可能更容易理解:
string input = "AAA-1111,AAA-666,SMT-QWQE,SMT-TTTR";
Dictionary<string, string> output = input.Split(',') // first split by ','
.Select(el => el.Split('-')) // then split each inner element by '-'
.GroupBy(el => el.ElementAt(0), el => el.ElementAt(1)) // group by the part that comes before '-'
.ToDictionary(grp => grp.Key, grp => string.Join(",", grp)); // convert to a dictionary with comma separated values
-
output["AAA"] // 1111,666
output["SMT"] // QWQE,TTTR