正则表达式提取符匹配字符串中的每第四个逗号

时间:2015-07-16 08:28:03

标签: c# asp.net regex parsing

我正在尝试创建一个正则表达式来获取下面字符串的输出,以4个逗号分隔值的集合。我尝试了一些东西,但它只选择每个逗号分隔值。我不知道如何获得所需的输出。

我试过的正则表达式:

".*?"(?=,|$)

数据:

"T","Success","2","2","T","Success","6458960","1","F,"You do not have sufficient credit.","6458962","1"

渴望出来:

"T","Success","2","2"  
"T","Success","6458960","1"  
"F,"You do not have sufficient credit.","6458962","1"

更新:" F也是双引号,这是一个错字,抱歉!"

" T""成功"" 2"" 2"" T"&# 34;成功"," 6458960"," 1"," F","您没有足够的信用。", " 6458962"" 1"

5 个答案:

答案 0 :(得分:1)

您只需要String.Split并且:

string[] fields = str.Split(',');
for (int i = 0; i < fields.Length; i += 4)
    Console.WriteLine(string.Join(",", fields.Skip(i).Take(4)));

输出:

"T","Success","2","2"
"T","Success","6458960","1"
"F,"You do not have sufficient credit.","6458962","1"

这假设这不是真正的csv数据。否则我建议使用真实的CSV parser that supports quoting characters。但似乎它们无论如何都被打破了(,"1","F,.,所以F没有用引号括起来。)

答案 1 :(得分:1)

您可以使用以下正则表达式,但前提是F也在括号中:

((?:".+",){3}(?:".+"))

这导致:

比赛1 1. [0-21] "T","Success","2","2"

比赛2 1. [22-49] "T","Success","6458960","1"

比赛3 1. [50-104] "F","You do not have sufficient credit.","6458962","1"

Regex Demo

如果数据确实是这种不一致的形式,您必须手动解析它或使用或条件修改正则表达式。

答案 2 :(得分:0)

((?:"[^"]*"|[^,"])*(?:,(?:"[^"]*"|[^,"])*){3}),?
  1. (?:"[^"]*"|[^,"])*将匹配逗号之间的值,可选择引用。报价将转义为""

  2. (X(?:,X){3}),?其中X是模式#1,将匹配四个逗号分隔值的序列,以及一个可选的尾随逗号。必须使用逗号才能正确匹配空值(,,foo,)。

  3. 如果保证值始终有引号,您可以删除|[^,"],?

答案 3 :(得分:0)

你可以试试这个正则表达式,但是正则表达式有一个问题:你需要修剪一下Comma,甚至还有更多Comma字符串,而不是4 Comma的倍数},它也可以正常工作

string patten = @"(?<=^(?:(?:[^,]*,){4})+)";
string text = @"""T"",""Success"",""2"",""2"",""T"",""Success"",""6458960"",""1"",""F,""You do not have sufficient credit."",""6458962"",""1""";
foreach (var tmp in Regex.Split(text, patten))
{
    Console.WriteLine(tmp.TrimEnd(','));
}

答案 4 :(得分:0)

我会避免使用正则表达式,除非你真的需要它,通常它们可能更难理解。

这里有趣的是Linq解决方案:

var data = @"""T"",""Success"",""2"",""2"",""T"",""Success"",""6458960"",""1"",""F,""You do not have sufficient credit."",""6458962"",""1""";

var res = data.Split(',')
            .Select((x ,i) => new { Pos = i / 4, Val = x })
            .GroupBy(x => x.Pos)
            .Select(g => string.Join(",", g.Select(x => x.Val)));