拆分字符串\"进入数组

时间:2016-02-15 14:10:51

标签: c# regex

我有一个复杂的字符串,里面有很多垃圾但其结构基本上是

"\"test\"  \"--test\" \"test\" \"--test\" \"test\" \"--test\" \"test\" \"--test\" \"test\" \"--test\" \"test\" \"--test\" \"--test\" \"test\" \"--test\" \"test\" \"--test\" \"test\"\"--test\" \"--test\" \"--test\" \"--test\" \"--test\" \"test\" \"--test\" \"--test\" \" test \"";

我想将\"之间的所有字符串拆分为27个元素的数组。当我使用我的正则表达式String[] waddup = Regex.Split(test, "\"\\s+\"");时,它几乎可以使用它,但会留下尾随\"

分割后的预期数组:

  

string [] expectedResult = new string [3] {" test"," - test"," test"," - test& #34;," test"," - test"," test"," - test"," test&# 34;," - test"," test"," - test"," test"   " - test"," test"," - test"," test"," - test" ,"测试"};

任何想法如何干净利落?

2 个答案:

答案 0 :(得分:2)

如果您更喜欢使用正则表达式匹配双引号内的字符串,您可以考虑:

string line = "\"test\"  \"--test\" \"test\" \"--test\" \"test\" \"--test\" \"test\" \"--test\" \"test\" \"--test\" \"test\" \"--test\" \"--test\" \"test\" \"--test\" \"test\" \"--test\" \"test\"\"--test\" \"--test\" \"--test\" \"--test\" \"--test\" \"test\" \"--test\" \"--test\" \" test \"";
// or    splts = Regex.Matches(line, "(?:^|\\s)\"([^\"]*)\"")
string[] splts = Regex.Matches(line, "\"([^\"]+)\"")
    .Cast<Match>()
    .Select(p=>p.Groups[1].Value)
    .ToArray();

这样,使用.ToArray()splts将是string[]类型的变量。请参阅IDEONE demo

我可以建议2个正则表达式,最短的是\"([^\"]+)\"

  • \" - 匹配前导"
  • ([^\"]+) - 匹配并捕获"
  • 以外的一个或多个字符
  • \" - 匹配尾随"

答案 1 :(得分:1)

尝试使用 string.Split 使用 StringSplitOptions 删除空条目(如果您的目的是获取所有 test 字符串):< / p>

var waddup = test.Split(new[] { "\\\"" }, StringSplitOptions.RemoveEmptyEntries);

使用完整的控制台示例:

using System;
using System.IO;
using System.Linq;

public class Test
{
    public static void Main()
    {
        var line = "\"test\"  \"--test\" \"test\" \"--test\" \"test\" \"--test\" \"test\" \"--test\" \"test\" \"--test\" \"test\" \"--test\" \"--test\" \"test\" \"--test\" \"test\" \"--test\" \"test\"\"--test\" \"--test\" \"--test\" \"--test\" \"--test\" \"test\" \"--test\" \"--test\" \" test \"";
        var splts = line.Split(new[]{"\\\""}, StringSplitOptions.RemoveEmptyEntries);
        Console.WriteLine(string.Join("\n", splts));
    }
}
相关问题