C#Regex Split - 引号外的逗号

Joã*_*ira 38 c# regex

我有很多字符串(实际上是SQL代码段),格式如下:

('ABCDEFG', 123542, 'XYZ 99,9')
Run Code Online (Sandbox Code Playgroud)

我需要使用C#拆分此字符串,以获得:

  • 'ABCDEFG'
  • 123542
  • 'XYZ 99,9'

我最初使用的是一个简单的Split(','),但由于最后一个参数中的逗号导致输出中的破坏,我需要使用Regex来获取它.问题是我在正则表达式中仍然相当无趣,我似乎无法破解模式主要是因为在该字符串内部,数字和字母数字参数可能随时存在......

我可以用什么来根据引号之外的每个逗号分割该字符串?干杯

Jen*_*ens 71

您可以拆分所有逗号,它们后面都有偶数引号,使用以下正则表达式来查找它们:

",(?=(?:[^']*'[^']*')*[^']*$)"
Run Code Online (Sandbox Code Playgroud)

你会喜欢它

var result = Regex.Split(samplestring, ",(?=(?:[^']*'[^']*')*[^']*$)");
Run Code Online (Sandbox Code Playgroud)

  • @MichaelNarinsky 带引号的字符串中的单引号一开始就无效。值 `'op','ID','script','Mike's','Content-Length' ` 无效,应为 `'op','ID','script','Mike''s',我相信“内容长度”仍然有效。(根据SQL字符串转义) (2认同)

Ris*_*god 15

我遇到了一个问题,它没有捕获空列。我这样修改它以获得空字符串结果

var results = Regex.Split(source, "[,]{1}(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))");
Run Code Online (Sandbox Code Playgroud)


小智 14

//this regular expression splits string on the separator character NOT inside double quotes. 
//separatorChar can be any character like comma or semicolon etc. 
//it also allows single quotes inside the string value: e.g. "Mike's Kitchen","Jane's Room"
Regex regx = new Regex(separatorChar + "(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))"); 
string[] line = regx.Split(string to split);
Run Code Online (Sandbox Code Playgroud)


pas*_*ool 6

虽然我在某些时候也喜欢挑战,但这实际上不是一个.请阅读这篇文章http://secretgeek.net/csv_trouble.asp ,然后继续使用http://www.filehelpers.com/

[Edit1,3]: 或者这篇文章也可以提供帮助(链接只显示一些VB.Net示例代码,但仍然可以将它与C#一起使用!):http://msdn.microsoft.com/en-us /library/cakac7e6.aspx

我试过为C#做示例(在项目中添加对Microsoft.VisualBasic的引用)

using System;
using System.IO;
using Microsoft.VisualBasic.FileIO;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            TextReader reader = new StringReader("('ABCDEFG', 123542, 'XYZ 99,9')");
            TextFieldParser fieldParser = new TextFieldParser(reader);

            fieldParser.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited;
            fieldParser.SetDelimiters(",");

            String[] currentRow; 

            while (!fieldParser.EndOfData)
            {
                try
                {
                     currentRow = fieldParser.ReadFields();

                     foreach(String currentField in currentRow)
                     {
                        Console.WriteLine(currentField);                        
                     }
                }
                catch (MalformedLineException e)
                {
                    Console.WriteLine("Line {0} is not valid and will be skipped.", e);
               }

            } 

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

[Edit2]: 找到另一个可能有帮助的地方:http://www.codeproject.com/KB/database/CsvReader.aspx

- 莱因哈德

  • @Hal:只是因为示例代码是VB并不意味着你不能在C#中使用它(添加对Microsoft.VisualBasic的引用并使用Microsoft.VisualBasic.FileIO添加;你可以使用TextFieldParser) (3认同)