根据空格分割字符串,但忽略引号中的字符串

joe*_*joe 1 c# regex

我想根据白色分割一个字符串,但是我知道字符串的某些部分将用引号引起来,并且其中会有空格,所以我不希望它分割封装在双引号中的字符串。

        if (file == null) return;
        else
        {
            using (StreamReader reader = new StreamReader(file))
            {
                string current_line = reader.ReadLine();
                string[] item;
                do
                {
                    item = Regex.Split(current_line, "\\s+");
                    current_line = reader.ReadLine();
                    echoItems(item);
                }
                while (current_line != null);

            }
        }
Run Code Online (Sandbox Code Playgroud)

上面的分割将分割,即使它被引用,例如“大城市”会出现在我的数组中:

0:“大

1:城镇”

编辑:在尝试@vks答案后,我只能让IDE接受所有引号:Regex.Split(current_line, "[ ](?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");

Item 是一个数组,我的 print 方法在打印数组内容时在每个元素周围放置一个“[]”。这是我的输出:

[0  0   0   1   2   1   1   1   "Album"                 6   6   11  50  20  0   0   0   40  40  0   0   0   1   1] [] [1] [] [1] [] [1] [] [1] [] [1] [] [1] [] [1  0   0   1   3   1   1   1   "CD case"               3   3   7   20  22  0   0   0   60  0   0   0   0   1   1] [] [1] [] [1] [] [1] [] [1] [] [1] [] [1]
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,拆分后,当每个元素都应该被分解时,它会将字符串的很大一部分放入单个元素中。

这是我尝试拆分的文件中的一行:

0   0   0   1   2   1   1   1   "CD case"                   6   6   11  50  20  0   0   0   40  40  0   0   0   1   1  1  1  1  1  1  1
Run Code Online (Sandbox Code Playgroud)

vks*_*vks 5

[ ](?=(?:[^"]*"[^"]*")*[^"]*$)
Run Code Online (Sandbox Code Playgroud)

按此拆分。请参阅演示。

https://regex101.com/r/sJ9gM7/56

这实质上是说[ ]==捕获一个空间。

(?=..)如果它前面有偶数个,即前面"有组。但它前面"somehing"不应该有奇数个。"

string strRegex = @"[ ](?=(?:[^""]*""[^""]*"")*[^""]*$)";
Regex myRegex = new Regex(strRegex, RegexOptions.Multiline);
string strTargetString = @"asdasd asdasd asdasdsad ""asdsad sad sa d sad""     asdasd asdsad "" sadsad asd sa dasd""";

return myRegex.Split(strTargetString);
Run Code Online (Sandbox Code Playgroud)