在多字符分隔符上拆分字符串

时间:2015-03-11 11:15:27

标签: c# .net

string Idstr="ID03I010102010210AEMPD4677EID03I020102020208L8159734ID03I030102030210IPS1406974PT03T010109981815938030202PT03T0201109899488666030201PT03T0301109818159381030203PT03T040112919818159381030201";

string[] stringSeparators = new string[] { "ID03I0" };
string[] result;

result = IdStr.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);

结果如下:

result[0]=10102010210AEMPD4677E
result[1]=20102020208L8159734
result[3]=30102030210IPS1406974PT03T010109981815938030202PT03T0201109899488666030201PT03T0301109818159381030203PT03T040112919818159381030201

期望的结果:

result[0]=ID03I010102010210AEMPD4677E
result[1]=ID03I020102020208L8159734
result[3]=ID03I030102030210IPS1406974PT03T010109981815938030202PT03T0201109899488666030201PT03T0301109818159381030203PT03T040112919818159381030201

如您所见,我想在元素中包含分隔符 ID03I0

注意:我知道我可以通过硬编码来包含它。但这不是我想要的方式。

2 个答案:

答案 0 :(得分:3)

result = IdStr.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)
    .Select(x => stringSeparators[0] + x).ToArray();

这会将分隔符添加到数组中每个元素的开头。

编辑:不幸的是,通过这种方法,您只能使用一个分隔符。因此,如果您想添加更多,请使用Regex。

答案 1 :(得分:2)

遵循正则表达式模式应该有效。

string input = "ID03I010102010210AEMPD4677EID03I020102020208L8159734ID03I030102030210IPS1406974PT03T010109981815938030202PT03T0201109899488666030201PT03T0301109818159381030203PT03T040112919818159381030201";  
string delimiter = "ID03I0";//Modify it as you need
string pattern = string.Format("(?<=.)(?={0})", delimiter);
string[] result = Regex.Split(input, pattern);

Online Demo

改编自this answer