请原谅标题是否含糊
我有一个这样的字符串:var curStr = "39bta,1q7l,vlaya,zkfaa,bc[ke],cc[b7ic,h7ko,c4ic]";
我需要做的是选择所有ID,除了,直接位于[
后面(不是bc
或cc
)
我尝试了以下问题:
var initSplit = curStr.Split('[');
var count = initSplit.Count();
List<String> z = new List<string>();
for (int i = 0; i < count; i++)
{
var y = initSplit[i].Split(',');
var i1 = i;
var t = y.Where(x => x != initSplit[i1].Split(',').Last()).ToList();
z.AddRange(t.Select(u => u.Replace("]", String.Empty)));
}
var stringArray = String.Join(",", z.ToArray());
这正是我想要的方式,并将其置于CSL 中,但它忽略了最后一项(c4ic
- 可能是因为.Last()部分)。有没有更干净或更优雅的方式呢?
答案 0 :(得分:3)
一行教会:
var x = curStr
.Split(',')
.Select(y => y.Contains('[') ? y.Split('[').Skip(1).First() : y )
.Select(z => z.Replace("]",string.Empty));
答案 1 :(得分:0)
这样的事情应该有效:
// If you don't need ] let's remove it first and split on comma
var parts = curStr.Replace("]","").Split(',');
// get the parts that contains [,
// split them and get only those parts that comes after [
// by checking the index
var p2 = parts
.Where(x => x.Contains("["))
.SelectMany(x => x.Split('[').Where((a, idx) => idx % 2 != 0));
// concat them into one list
var result = parts.Where(x => !x.Contains('[')).Concat(p2).ToList();
这不会处理bc[[
等案例,您也可以使用x.Split(new [] { '[' }, StringSplitOptions.RemoveEmptyEntries)
来处理这些案件。
答案 2 :(得分:0)
主要问题是拉出内部物品。如果你用逗号分隔,你会有cc[b7ic
之类的项目。然后你可以使用正则表达式摆脱前面部分:
var items = curStr
.Split(',')
.Select(item => Regex.Replace(item, @"[^\[]*\[(.*)", "$1").Replace("]", ""));
var result = string.Join(",",items);
答案 3 :(得分:0)
您可以使用此正则表达式:
string pattern = @"\,([a-z]*)\[";
string replacement = ",";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(curStr, replacement);
result = result.Replace("]","");
string[] array_result = result.Split(',');