拆分具有空格的字符串,除非它们包含在“引号"中? [英] Split a string that has white spaces, unless they are enclosed within "quotes"?

查看:24
本文介绍了拆分具有空格的字符串,除非它们包含在“引号"中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让事情变得简单:

string streamR = sr.ReadLine();  // sr.Readline results in:
                                 //                         one "two two"

我希望能够将它们保存为两个不同的字符串,删除除引号之间的空格之外的所有空格.因此,我需要的是:

I want to be able to save them as two different strings, remove all spaces EXCEPT for the spaces found between quotation marks. Therefore, what I need is:

string 1 = one
string 2 = two two

到目前为止,我发现有效的是以下代码,但它删除了引号内的空格.

So far what I have found that works is the following code, but it removes the spaces within the quotes.

//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

我已经研究了 正则表达式在空格上拆分,除非在引号中 但是我似乎无法让正则表达式工作/理解代码,尤其是如何拆分它们使它们成为两个不同的字符串.那里的所有代码都给我一个编译错误(我正在使用 System.Text.RegularExpressions)

I have looked into Regular Expression to split on spaces unless in quotes however I can't seem to get regex to work/understand the code, especially how to split them so they are two different strings. All the codes there give me a compiling error (I am using 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();

这篇关于拆分具有空格的字符串,除非它们包含在“引号"中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆