【发布时间】:2015-06-11 22:30:22
【问题描述】:
我想分割一个基于白色的字符串,但是我知道我的字符串的某些部分会用引号引起来,并且会有空格,所以我不希望它分割封装在双引号中的字符串.
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, "[ ](?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");
Item 是一个数组,当打印出数组内容时,我的打印方法会在每个元素周围放置一个“[]”。这是我的输出:
[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
【问题讨论】: