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

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

问题描述

简单起见:

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

推荐答案

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天全站免登陆