6

我有一个关于拆分字符串的问题。我想拆分字符串,但是当在字符串中看到字符“”时,不要拆分并删除空格。

我的字符串:

String tmp = "abc 123 \"Edk k3\" String;";

结果:

1: abc
2: 123
3: Edkk3  // don't split after "" and remove empty spaces
4: String

我的结果代码,但我不知道如何删除“”中的空格

var tmpList = tmp.Split(new[] { '"' }).SelectMany((s, i) =>
                {
                    if (i % 2 == 1) return new[] { s };
                    return s.Split(new[] { ' ', ';' }, StringSplitOptions.RemoveEmptyEntries);
                }).ToList();

或者,但这没有看到“”,所以它分裂了一切

string[] tmpList = tmp.Split(new Char[] { ' ', ';', '\"', ',' }, StringSplitOptions.RemoveEmptyEntries);
4

3 回答 3

8

添加 .Replace(" ","")

String tmp = @"abc 123 ""Edk k3"" String;";
var tmpList = tmp.Split(new[] { '"' }).SelectMany((s, i) =>
{
    if (i % 2 == 1) return new[] { s.Replace(" ", "") };
    return s.Split(new[] { ' ', ';' }, StringSplitOptions.RemoveEmptyEntries);
}).ToList();
于 2012-11-30T13:16:00.257 回答
0

string.Split不适合你想做的事情,因为你不能告诉它忽略".

我也不会去Regex,因为这会变得复杂且占用大量内存(对于长字符串)。

实现您自己的解析器 - 使用状态机来跟踪您是否在引用的部分内。

于 2012-11-30T13:16:36.157 回答
0

您可以使用正则表达式。不要拆分,而是指定要保留的内容。

例子:

string tmp = "abc 123 \"Edk k3\" String;";

MatchCollection m = Regex.Matches(tmp, @"""(.*?)""|([^ ]+)");

foreach (Match s in m) {
  Console.WriteLine(s.Groups[1].Value.Replace(" ", "") + s.Groups[2].Value);
}

输出:

abc
123
Edkk3
String;
于 2012-11-30T13:24:01.233 回答