XML technologies / Regular expressions / Practical regex techniques / Detailed examples / Processing CSV files
(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)
Reading and parsing CSV files (Comma Separated Values) can be tricky. Sometimes it seems that every program generating CSV files defines its own CSV format.
I will begin with a program that reads the CSV files generated by Microsoft Excel; we will later generalize for other variants. The final version for Microsoft CSV data is in The art of writing regular expressions (under Unrolling loops for CSV data), incorporating this chapter’s efficiency considerations. Microsoft’s format is also among the simpler ones: comma-separated values are either bare, simply between commas, or enclosed in double quotes. A quote appearing within a quoted field is doubled.
An example:
Zehn Tausender,10000, 2710 ,,"10,000","Das warfln ""10 große Scheine"", Baby",10K
The line contains seven fields:
Zehn● Tausender 10000 ●2710●
(an empty field)10,000 Das● war'n● "10● große● Scheine",● Baby 10K
To parse this line, we need an expression recognizing both value types. Bare values are easy: they may contain anything except quotes and commas, matched by ˹[^",]+˼.
Quoted values may contain commas, spaces, and anything except quotes. They may also contain two consecutive quotes, representing one quote in the actual value.
Following this recipe, we can match a quoted field with any number of ˹[^"]|""˼ inside ˹"..."˼, giving ˹"(?:[^"]|"")*"˼. Atomic groups, with ˹(?>...)˼ instead of ˹(?:...)˼, would be more efficient still. See The art of writing regular expressions under Using atomic groups and possessive quantifiers.
Combining these gives the regex ˹[^",]+|"(?:[^"]|"")*"˼ matching one field. This is already so hard to read that I had better use free-spacing mode (see Free-spacing mode):
[^",]+ # Entweder ein Feld ohne Kommas und Anführungszeichen ...
| # ... oder ...
# ... ein Feld in Anführungszeichen:
" # Öffnendes Anführungszeichen
(?: [^"] | "" )* # Anführungszeichen nur verdoppelt erlaubt
" # Schließendes AnführungszeichenWe can apply this regex repeatedly to a CSV line, but to extract actual values we must know which alternative matched. For a quoted field, we must remove the outer quotes and replace doubled inner quotes with single ones.
I can see two approaches. First, inspect the initial character: if it is a quote, remove the first and last characters, the outer quotes, then replace inner ›""‹ with ›"‹. That is straightforward, but capturing parentheses make it even easier. Inspect the captures afterward to see which alternative matched:
( [^",]+ ) # Entweder ein Feld ohne Kommas und Anführungszeichen ...
| # ... oder ...
# ... ein Feld in Anführungszeichen:
" # Öffnendes Anführungszeichen
( (?: [^"] | "" )* ) # Anführungszeichen nur verdoppelt erlaubt
" # Schließendes AnführungszeichenIf the first group captured text, use it as the value. If the second did, replace any ›""‹ with ›"‹.
This gives a Perl program that I will later present, after some debugging, rewritten in Java and VB.NET. A PHP version appears in PHP under Processing CSV files with PHP. We assume the CSV line is in the variable $zeile and its final newline has already been removed, since it is not part of the last value.
while ($zeile =~ m{
( [^",]+ ) # Ein Feld ohne Kommas und Anführungszeichen ...
| # ... oder ...
# ... ein Feld in Anführungszeichen:
" # Öffnendes Anführungszeichen
( (?: [^"] | "" )* ) # Anführungszeichen nur verdoppelt erlaubt
" # Schließendes Anführungszeichen
}gx)
{
if (defined $1) {
$feld = $1;
} else {
$feld = $2;
$feld =~ s/""/"/g;
}
print "[$feld]"; # Feld für Debugging-Zwecke ausgeben.
.. . # Wert in $feld kann jetzt weiterverarbeitet werden.
}With our test data, we obtain:
[Zehn●Tausender][10000][●2710●][10,000][Das●war'n●"10●große●Scheine",●Baby][10K]
That looks good, but unfortunately the empty fourth field yields nothing. If fields are stored in an array, for example, we want the fifth element to contain »10,000«. That requires matching empty fields and storing corresponding empty array elements.
We could simply replace ˹[^",]+˼ with ˹[^",]*˼, allowing the first alternative to match empty fields too. Obvious, perhaps—but does it work?
Let us try. We get:
[Zehn●Tausender][][10000][][●2710●][][][][10,000][][][Das●war'n●"...",●Baby][][10K][]
Oops: many extra empty fields! On reflection, this should not be too surprising. With ˹(...)*˼, a zero-length match is possible. We want this for a truly empty field, but after matching the first field, the regex engine starts the second iteration at ›Zehn●Tausender▵,10000...‹. Nothing matches the comma, but star now allows an empty string at that exact position to succeed. In principle this could be found forever, but the transmission advances one character after a successful empty match (see End of the previous match or start of the current one?). We therefore get an empty match between every real match, an additional empty match before every quoted field, and one at the string’s end.
Disabling the transmission
We relied on the transmission to move past the comma after every iteration of /g. We can solve the problem by doing this ourselves without using the transmission. There are two possibilities:
Explicitly match commas in the regex. Matching the comma then belongs to matching the field, and we traverse the entire string, matching every character.
Check for each field that we are at a valid field-start position: either the string’s beginning or just after a comma.
Better yet, combine both. The first approach can require every field except the first to begin with comma. Conversely, require every field except the last to end with comma. Prepend ˹^|,˼ to our regex, or append ˹$|,˼, adding the required parentheses.
We try ˹^|,˼ and get:
(?:^|,)
(?:
( [^",]* ) # Entweder ein Feld ohne Kommas und Anführungszeichen ...
| # ... oder ...
# ... ein Feld in Anführungszeichen:
" # Öffnendes Anführungszeichen
( (?: [^"] | "" )* ) # Anführungszeichen nur verdoppelt erlaubt
" # Schließendes Anführungszeichen
)This really should work, but adding it to our program gives:
[Zehn●Tausender][10000][●2710●][][][000][][●Baby][10K]
We expected:
[Zehn●Tausender][10000][●2710●][][10,000][Das●war'n●"10●große●Scheine",●Baby][10K]
Why did it fail this time? Are quoted fields a problem? No, the problem arises earlier. Recall the lesson from Exploiting ordered alternation: When several alternatives can match the same text, consider their order carefully. The first alternative, ˹[^",]*˼ , also succeeds with an empty string, so the second is never used unless something later in the regex forces it. Nothing follows our alternatives, so the second is never used!
That deserves another thought. Let us try again with the alternatives reversed:
(?:^|,)
(?: # Entweder ein Feld in Anführungszeichen ...
" # Öffnendes Anführungszeichen
( (?: [^"] | "" )* ) # Anführungszeichen nur verdoppelt erlaubt
" # Schließendes Anführungszeichen
| # ... oder ...
( [^",]+ ) # ... ein ›nacktes‹ Feld ohne Kommas und Anführungszeichen.
)It works! At least with our test data. Could other data make it fail? More testing cannot hurt. But this section is called “Disabling the transmission”, and the metacharacter ˹\G˼ ensures every iteration of /g starts exactly where the last ended. We suspect this already happens, since our regex is designed to recognize every character. Adding ˹\G˼ at the regex’s beginning prohibits matches requiring the transmission to advance. We expect none, but if they occur, the error becomes more obvious. Had we done so with the preceding incorrect regex, instead of
[Zehn●Tausender][10000][●2710●][][][000][][●Baby][10K]
we would have obtained the equally incorrect
[Zehn●Tausender][10000][●2710●][][]
, immediately revealing the problem.
Parsing CSV files with Java
Here is the CSV example using Sun’s java.util.regex package. It prioritizes clarity and readability; a more efficient version appears in Java (under Processing CSV data).
import java.util.regex.*;
Pattern regex = Pattern.compile(
"\\G(?:^|,) \n"+
"(?: \n"+
" # Entweder ein Feld in Anführungszeichen ... \n"+
" \" # Öffnendes Anführungszeichen \n"+
" ( (?: [^\"]++ | \"\" )*+ ) \n"+
" \" # Schließendes Anführungszeichen \n"+
" # ... oder ... \n"+
" | \n"+
" # ... ein Feld ohne Kommas und Anführungszeichen ... \n"+
" ( [^\",]* ) \n"+
" ) \n", Pattern.COMMENTS);
Pattern AnfzeichenRegex = Pattern.compile("\"\"");
// Aus dem CSV-String in ’Zeile’ alle Felder extrahieren ...
Matcher m = regex.matcher(Zeile);
while (m.find())
{
String Feld;
if (m.group(1) != null) {
Feld = AnfzeichenRegex.matcher(m.group(1)).replaceAll("\"");
} else {
Feld = m.group(2);
}
// Wert in ’Feld’ kann jetzt weiterverarbeitet werden.
System.out.println("[" + Feld + "]");
}Another approach
We described two ways to keep our subexpressions synchronized with CSV fields. The second ensures a match starts only where a field can begin. Superficially, this resembles prepending ˹^|˼ to our regex, but uses lookbehind instead: ˹(?<=^|,)˼.
Unfortunately, many programs supporting lookbehind allow only fixed-length strings (see Lookahead and lookbehind), preventing this approach. To address only that limitation, replace ˹(?<=^|,)˼ with ˹(?:^|(?<=,))˼, but that is needlessly complicated. It also relies again on the transmission to skip each comma. An error elsewhere could wrongly start matching at a position such as ›..."10,▵000"...‹. Overall, the first approach seems safer.
We can still rescue this approach by requiring a field to end before comma or the string’s end. Appending ˹(?=$|,)˼ to our regex ensures only fields ending there are found. In practice, one would probably omit it, but knowing several routes to the same goal is useful.
A more efficient regex
We will address efficiency properly only in The art of writing regular expressions. Still, atomic groups can greatly improve this regex (see Atomic parentheses). Where supported, replace the subexpression ˹(?:[^"]|"")*˼ matching quoted-field values with ˹(?>[^"]+|"")*˼. The following VB.NET example does this.
With possessive quantifiers (see Possessive quantifiers), as supported by Sun’s Java package, an equivalent formulation is possible; see the preceding Java example.
The reasoning is discussed in The art of writing regular expressions and leads to the still more efficient version in Unrolling loops for CSV files.
Processing CSV files with VB.NET
Imports System.Text.RegularExpressions
Dim FeldRegex as Regex = New Regex( _
"(?:^|,) " & _
"(?: " & _
" (?# Entweder ein Feld in Anführungszeichen ... ) " & _
" "" (?# Öffnendes Anführungszeichen ) " & _
" ( (?> [^""]+ | """" )* ) " & _
" "" (?# Schließendes Anführungszeichen ) " & _
" (?# ... oder ...) " & _
" | " & _
" (?# ... ein Feld ohne Kommas und Anführungszeichen. ) " & _
" ( [^"",]* ) " & _
" )", RegexOptions.IgnorePatternWhitespace)
Dim AnfzRegex as Regex = New Regex("""""") 'Ein String mit zwei Anführungszeichen.
.
.
.
Dim FeldMatch as Match = FeldRegex.Match(Zeile)
While FeldMatch.Success
Dim Feld as String
If FeldMatch.Groups(1).Success
Feld = AnfzRegex.Replace(FeldMatch.Groups(1).Value, """")
Else
Feld = FeldMatch.Groups(2).Value
End If
Console.WriteLine("[" & Feld & "]")
' Wert in ’Feld’ kann jetzt weiterverarbeitet werden.
FeldMatch = FeldMatch.NextMatch
End WhileOther CSV formats
Microsoft’s CSV format is common because it comes from Microsoft, but other programs differ slightly. I have encountered many variations:
Some use another separator, such as
›;‹or tab. One might then wonder whether to keep calling it CSV, “Comma Separated Values”.Sometimes, a separator may be followed by whitespace not belonging to the field’s value.
Often, inner quotes are escaped with a backslash instead of doubled:
›\"‹instead of›""‹inside a quoted field. This usually also means a backslash before any other character is ignored.
These changes are easy to implement. For the first, replace every regex comma with the separator. For the second, append ˹\s*˼ to the first separator, making the regex begin with ˹(?:^|,\s*)˼.
For the third, reuse code developed earlier (see Allowing escaped quotes inside quoted strings), replacing ˹[^"]+|""˼ with ˹[^"\\]+|\\˼. Naturally, the following s/""/"/g must be replaced by the more general s/\\(.)/$1/g or an equivalent in the language used.
German edition copyright © 2008 by O’Reilly Verlag GmbH & Co. KG
You may print the online version for private use.
Otherwise, this chapter from "Reguläre Ausdrücke" is subject to the same terms as the bound edition: the work and all its parts are protected by copyright. All rights reserved, including reproduction, translation, microfilming, storage and processing in electronic systems.
O’Reilly Verlag GmbH & Co. KG, Balthasarstr. 81, 50670 Köln