Split constantly on the last delimiter in C#
我有以下字符串:
1 | string x ="hello;there;;you;;;!;" |
我想要的结果是长度为4的列表,带有以下子字符串:
1 2 3 4 | "hello" "there;" "you;;" "!" |
换句话说,当定界符重复多次时,如何在最后一次出现时拆分?谢谢。
您需要使用基于正则表达式的拆分:
1 2 3 4 | var s ="hello;there;;you;;;!;"; var res = Regex.Split(s, @";(?!;)").Where(m => !string.IsNullOrEmpty(m)); Console.WriteLine(string.Join(",", res)); // => hello, there;, you;;, ! |
请参阅C#演示
为避免在字符串末尾与
您似乎不想删除空条目,但要保留分隔符。
您可以使用以下代码:
1 2 3 4 5 6 7 | string s ="hello;there;;you;;;!;"; MatchCollection matches = Regex.Matches(s, @"(.+?);(?!;)"); foreach(Match match in matches) { Console.WriteLine(match.Captures[0].Value); } |
1 2 3 4 5 | string x ="hello;there;;you;;;!;" var splitted = x.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptryEntries); foreach (var s in splitted) Console.WriteLine("{0}", s); |