2015-04-07 79 views
0

我想分割基于白色的字符串,但是我知道我的字符串的某些部分将在引号中,并且在其中会有空格,所以我没有希望它能够拆分封装在双引号中的字符串。根据空格拆分字符串,但忽略引号中的那些

 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); 

      } 
     } 

拆分会分裂上面会分裂,即使它引用,例如 “大镇” 成为我的数组:

0: “大

1:镇”

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

项目是一个数组,我的打印方法将“[]”aroun d打印出数组内容时的每个元素。这是我的输出:

[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] 

正如你可以拆分它是把字符串的很大一部分到一个单一的元素,当每一种应该被分解后看到。

以下是文件中的一行,我试图分裂:

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 

回答

2
[ ](?=(?:[^"]*"[^"]*")*[^"]*$) 

斯普利特this.See演示。

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

这本质上说[ ] ==捕获的空间。

(?=..)向前看,如果有偶数个"提前"somehing" it.i.e组提前它。但是它不应该有一个奇怪的"在它前面的。

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); 
+0

请你能解释一下吗? – vivoconunxino

+0

@vivoconunxino check编辑 – vks

+0

了解它,感谢分享 – vivoconunxino

相关问题