为了让事情变得简单:
string streamR = sr.ReadLine(); // sr.Readline results in:
// one "two two"
我希望能够将它们保存为两个不同的字符串,删除除引号之间的空格之外的所有空格。因此,我需要的是:
string 1 = one
string 2 = two two
到目前为止,我发现以下代码有效,但它删除了引号内的空格。
//streamR.ReadLine only has two strings
string[] splitter = streamR.Split(' ');
str1 = splitter[0];
// Only set str2 if the length is >1
str2 = splitter.Length > 1 ? splitter[1] : string.Empty;
其输出变为
one
two
我调查过正则表达式按空格分割,除非用引号引起来 https://stackoverflow.com/questions/554013/regular-expression-to-split-on-spaces-unless-in-quotes但是我似乎无法让正则表达式工作/理解代码,特别是如何拆分它们,使它们成为两个不同的字符串。那里的所有代码都会给我一个编译错误(我正在使用System.Text.RegularExpressions
)
string input = "one \"two two\" three \"four four\" five six";
var parts = Regex.Matches(input, @"[\""].+?[\""]|[^ ]+")
.Cast<Match>()
.Select(m => m.Value)
.ToList();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)