C#,正则表达式:如何解析逗号分隔的值,其中某些值可能用引号引起来,字符串本身包含逗号

在C#中,使用Regex该类,如何解析逗号分隔的值,其中某些值可能被引号括起来的包含逗号的字符串本身?


using System ;

using System.Text.RegularExpressions ;


class  Example

    {

    public static void Main ( )

        {

        string  myString  =  "cat,dog,\"0 = OFF, 1 = ON\",lion,tiger,'R = red, G = green, B = blue',bear" ;

        Console.WriteLine ( "\nmyString is ...\n\t" + myString + "\n" ) ;

        Regex   regex  =  new Regex  (  "(?<=,(\"|\')).*?(?=(\"|\'),)|(^.*?(?=,))|((?<=,).*?(?=,))|((?<=,).*?$)"  )  ;

        Match   match  =  regex.Match ( myString ) ;

        int j = 0 ;

        while ( match.Success )

            {

            Console.WriteLine ( j++ + " \t" + match ) ;

            match  =  match.NextMatch() ;

            }

        }

    }

输出(部分)如下所示:


0       cat

1       dog

2       "0 = OFF

3        1 = ON"

4       lion

5       tiger

6       'R = red

7        G = green

8        B = blue'

9       bear

但是,所需的输出是:


0       cat

1       dog

2       0 = OFF, 1 = ON

3       lion

4       tiger

5       R = red, G = green, B = blue

6       bear


月关宝盒
浏览 907回答 3
3回答

千巷猫影

尝试使用此正则表达式:"[^"\r\n]*"|'[^'\r\n]*'|[^,\r\n]*&nbsp; &nbsp; Regex regexObj = new Regex(@"""[^""\r\n]*""|'[^'\r\n]*'|[^,\r\n]*");&nbsp; &nbsp; Match matchResults = regexObj.Match(input);&nbsp; &nbsp; while (matchResults.Success)&nbsp;&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine(matchResults.Value);&nbsp; &nbsp; &nbsp; &nbsp; matchResults = matchResults.NextMatch();&nbsp; &nbsp; }:猫狗“ 0 = OFF,1 = ON”狮子虎'R =红色,G =绿色,B =蓝色'熊注意:此正则表达式解决方案适用于您的情况,但是我建议您使用专用的库,例如FileHelpers。

慕标琳琳

为什么不听从专家的建议,不要滚动自己的CSV解析器。您的第一个想法是,“我需要在引号内处理逗号”。您的下一个想法是,“哦,糟糕,我需要处理引号内的引号。转义的引号。双引号。单引号...”这是通往疯狂的道路。不要自己写。查找具有广泛的单元测试覆盖面的库,该库涉及所有困难部分,并为您解决了所有困难。对于.NET,请使用免费的开源FileHelpers库。

慕森卡

只需添加我今天上午工作的解决方案。var regex = new Regex("(?<=^|,)(\"(?:[^\"]|\"\")*\"|[^,]*)");foreach (Match m in regex.Matches("<-- input line -->")){&nbsp; &nbsp; var s = m.Value;&nbsp;}如您所见,您需要每行调用regex.Matches()。然后,它将返回MatchCollection,其中具有与列相同数量的项目。显然,每个匹配项的Value属性都是解析后的值。这项工作仍在进行中,但它很乐意解析CSV字符串,例如:2,3.03,"Hello, my name is ""Joshua""",A,B,C,,,D
打开App,查看更多内容
随时随地看视频慕课网APP