Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
631 views
in Technique[技术] by (71.8m points)

regex - C#, regular expressions : how to parse comma-separated values, where some values might be quoted strings themselves containing commas

In C#, using the Regex class, how does one parse comma-separated values, where some values might be quoted strings themselves containing commas?

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 ( "
myString is ...
" + myString + "
" ) ;
        Regex   regex  =  new Regex  (  "(?<=,("|')).*?(?=("|'),)|(^.*?(?=,))|((?<=,).*?(?=,))|((?<=,).*?$)"  )  ;
        Match   match  =  regex.Match ( myString ) ;
        int j = 0 ;
        while ( match.Success )
            {
            Console.WriteLine ( j++ + " " + match ) ;
            match  =  match.NextMatch() ;
            }
        }
    }

Output (in part) appears as follows:

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

However, desired output is:

0       cat
1       dog
2       0 = OFF, 1 = ON
3       lion
4       tiger
5       R = red, G = green, B = blue
6       bear
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try with this Regex:

"[^"
]*"|'[^'
]*'|[^,
]*

    Regex regexObj = new Regex(@"""[^""
]*""|'[^'
]*'|[^,
]*");
    Match matchResults = regexObj.Match(input);
    while (matchResults.Success) 
    {
        Console.WriteLine(matchResults.Value);
        matchResults = matchResults.NextMatch();
    }

Ouputs:

  • cat
  • dog
  • "0 = OFF, 1 = ON"
  • lion
  • tiger
  • 'R = red, G = green, B = blue'
  • bear

Note: This regex solution will work for your case, however I recommend you to use a specialized library like FileHelpers.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...