regex to split line (csv file)

后端 未结 7 1852
予麋鹿
予麋鹿 2020-12-03 12:37

I am not good in regex. Can some one help me out to write regex for me?

I may have values like this while reading csv file.

\"Artist,Name\",Album,12-SCS
\         


        
7条回答
  •  感动是毒
    2020-12-03 13:00

    Actually, its pretty easy to match CVS lines with a regex. Try this one out:

    StringCollection resultList = new StringCollection();
    try {
        Regex pattern = new Regex(@"
            # Parse CVS line. Capture next value in named group: 'val'
            \s*                      # Ignore leading whitespace.
            (?:                      # Group of value alternatives.
              ""                     # Either a double quoted string,
              (?                # Capture contents between quotes.
                [^""]*(""""[^""]*)*  # Zero or more non-quotes, allowing 
              )                      # doubled "" quotes within string.
              ""\s*                  # Ignore whitespace following quote.
            |  (?[^,]*)         # Or... zero or more non-commas.
            )                        # End value alternatives group.
            (?:,|$)                  # Match end is comma or EOS", 
            RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace);
        Match matchResult = pattern.Match(subjectString);
        while (matchResult.Success) {
            resultList.Add(matchResult.Groups["val"].Value);
            matchResult = matchResult.NextMatch();
        } 
    } catch (ArgumentException ex) {
        // Syntax error in the regular expression
    }
    

    Disclaimer: The regex has been tested in RegexBuddy, (which generated this snippet), and it correctly matches the OP test data, but the C# code logic is untested. (I don't have access to C# tools.)

提交回复
热议问题