는 그 정규식이 "오른쪽"대답하지 동의하지만, 문제가 무엇을 요구하고 나는 좋은 정규식 도전을 좋아한다.
아래 패턴은 내 standard CSV parsing regex의 수정 된 버전으로 공백을 제거하고 요청한대로 CSV가 완벽하다고 가정합니다. 문제의 유일한 부분은 이스케이프/두배로 된 따옴표를 제거하지 않는다는 것입니다. 따옴표를 이스케이프 이스케이프 해제하는 예제는 패턴 뒤에 제공됩니다.이 각각의 비어 있지 않은 라인/레코드의 일치를 반환합니다 아래에 하나 개 이상의 라인/CSV 파일/스트림의 기록은 정규 표현식에 전달됩니다
. 각 일치 항목에는 캡처 된 값이 해당 라인/레코드에 포함 된 Value
이라는 캡처 그룹이 포함됩니다.
여기 주석 패턴입니다 (그것을 on Regexstorm.net 테스트) :
(?<=\r|\n|^)(?!\r|\n|$) // Records start at the beginning of line (line must not be empty)
(?: // Group for each value and a following comma or end of line (EOL) - required for quantifier (+?)
[^\S\r\n]* // Removes leading spaces
(?: // Group for matching one of the value formats before a comma or EOL
"(?<Value>(?:[^"]|"")*)"| // Quoted value -or-
(?<Value>[^,\r\n]+)| // Unquoted/open ended quoted value -or-
(?<Value>) // Empty value before comma (before EOL is excluded by "+?" quantifier later)
)
[^\S\r\n]* // Removes trailing spaces
(?:,|(?=\r|\n|$)) // The value format matched must be followed by a comma or EOL
)+? // Quantifier to match one or more values (non-greedy/as few as possible to prevent infinite empty values)
(?:(?<=,)(?<Value>))? // If the group of values above ended in a comma then add an empty value to the group of matched values
(?:\r\n|\r|\n|$) // Records end at EOL
여기 모든 의견이나 공백없이 원시 패턴입니다.
(?<=\r|\n|^)(?!\r|\n|$)(?:[^\S\r\n]*(?:"(?<Value>(?:[^"]|"")*)"|(?<Value>[^,\r\n]+)|(?<Value>))[^\S\r\n]*(?:,|(?=\r|\n|$)))+?(?:(?<=,)(?<Value>))?(?:\r\n|\r|\n|$)
는 그리고, 여기에 C#을 버전을 탈출합니다. 정규식 패턴을 사용하는 방법에 대한
String CSVPattern=
@"(?<=\r|\n|^)(?!\r|\n|$)" +
@"(?:" +
@"[^\S\r\n]*" +
@"(?:" +
@"""(?<Value>(?:[^""]|"""")*)""|" +
@"(?<Value>[^,\r\n]+)|" +
@"(?<Value>)" +
@")" +
@"[^\S\r\n]*" +
@"(?:,|(?=\r|\n|$))" +
@")+?" +
@"(?:(?<=,)(?<Value>))?" +
@"(?:\r\n|\r|\n|$)";
예는 (물론,이 패턴으로 대체 할 수있는 원래의 패턴) 비슷한 질문 here에 내 대답에 발견, 또는 C# pad here, 또는 here에 할 수 있습니다.
참고 : 위 예제는 아래와 같이 따옴표를 undoubling/이스케이프 취소에 대한 논리를 포함 :
if (Capture.Length == 0 || Capture.Index == Record.Index || Record.Value[Capture.Index - Record.Index - 1] != '\"')
{
// No need to unescape/undouble quotes if the value is empty, the value starts
// at the beginning of the record, or the character before the value is not a
// quote (not a quoted value)
Console.WriteLine(Capture.Value);
}
else
{
// The character preceding this value is a quote
// so we need to unescape/undouble any embedded quotes
Console.WriteLine(Capture.Value.Replace("\"\"", "\""));
}
왜 정규식? 당신은 그것을 사용해야 만합니까? – gdoron
CSV가 완전하게 유효하면 따옴표 붙은 필드에 줄 바꿈이 있습니다. – Joey
"split"방법이이 경우에 더 적절하다고 생각합니다. –