Regular Expressions Cookbook, 2nd Edition
by Steven Levithan
Published by
O'Reilly Media, Inc., 2012
and
Tags
A1 | B1 | C1 | D1 |
(omitted) | (omitted) | (omitted) | (omitted) |
The previous row was blank | B3 | (omitted) | (omitted) |
A4 | B4 | C4 | (omitted) |
%string% | (blank) | % | %% |
Your solution should define a function that parses a string
containing the entire contents of the file that needs to be imported.
You should use the application’s existing data structures RECTable, RECRow, and RECCell to store the tables imported from the
file.
static RECTable ImportTable(string fileContents) {
RECTable table = null;
RECRow row = null;
RECCell cell = null;
Regex regexObj = new Regex(
@" \b(?<keyword>table|row|cell)\b
| %(?<string>[^%]*(?:%%[^%]*)*)%
| (?<error>\S+)",
RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
Match match = regexObj.Match(fileContents);
while (match.Success) {
if (match.Groups["keyword"].Success) {
string keyword = match.Groups["keyword"].Value.ToLower();
if (keyword == "table") {
table = new RECTable();
row = null;
cell = null;
} else if (keyword == "row") {
if (table == null)
throw new Exception("Invalid data: row without table");
row = table.addRow();
cell = null;
} else if (keyword == "cell") {
if (row == null)
throw new Exception("Invalid data: cell without row");
cell = row.addCell();
} else {
throw new Exception("Parser bug: unknown keyword");
}
} else if (match.Groups["string"].Success) {
string content = match.Groups["string"].Value.Replace("%%", "%");
if (cell != null)
cell.addContent(content);
else if (row != null)
throw new Exception("Invalid data: string after row keyword");
else if (table != null)
table.addCaption(content);
else
throw new Exception("Invalid data: string before table keyword");
} else if (match.Groups["error"].Success) {
throw new Exception("Invalid data: " + match.Groups["error"].Value);
} else {
throw new Exception("Parser bug: no capturing group matched");
}
match = match.NextMatch();
}
if (table == null)
throw new Exception("Invalid data: table keyword missing");
return table;
}Function ImportTable(ByVal FileContents As String)
Dim Table As RECTable = Nothing
Dim Row As RECRow = Nothing
Dim Cell As RECCell = Nothing
Dim RegexObj As New Regex(
" \b(?<keyword>table|row|cell)\b" & _
"| %(?<string>[^%]*(?:%%[^%]*)*)%" & _
"| (?<error>\S+)",
RegexOptions.IgnoreCase Or RegexOptions.IgnorePatternWhitespace)
Dim MatchResults As Match = RegexObj.Match(FileContents)
While MatchResults.Success
If MatchResults.Groups("keyword").Success Then
Dim Keyword As String = MatchResults.Groups("keyword").Value
Keyword = Keyword.ToLower()
If Keyword = "table" Then
Table = New RECTable
Row = Nothing
Cell = Nothing
ElseIf Keyword = "row" Then
If Table Is Nothing Then
Throw New Exception("Invalid data: row without table")
End If
Row = Table.addRow
Cell = Nothing
ElseIf Keyword = "cell" Then
If Row Is Nothing Then
Throw New Exception("Invalid data: cell without row")
End If
Cell = Row.addCell
Else
Throw New Exception("Parser bug: unknown keyword")
End If
ElseIf MatchResults.Groups("string").Success Then
Dim Content As String = MatchResults.Groups("string").Value
Content = Content.Replace("%%", "%")
If Cell IsNot Nothing Then
Cell.addContent(Content)
ElseIf Row IsNot Nothing Then
Throw New Exception("Invalid data: string after row keyword")
ElseIf Table IsNot Nothing Then
Table.addCaption(Content)
Else
Throw New Exception("Invalid data: string before table keyword")
End If
ElseIf MatchResults.Groups("error").Success Then
Throw New Exception("Invalid data")
Else
Throw New Exception("Parser bug: no capturing group matched")
End If
MatchResults = MatchResults.NextMatch()
End While
If Table Is Nothing Then
Throw New Exception("Invalid data: table keyword missing")
End If
Return Table
End FunctionRECTable ImportTable(String fileContents) throws Exception {
RECTable table = null;
RECRow row = null;
RECCell cell = null;
final int groupkeyword = 1;
final int groupstring = 2;
final int grouperror = 3;
Pattern regex = Pattern.compile(
" \\b(table|row|cell)\\b\n" +
"| %([^%]*(?:%%[^%]*)*)%\n" +
"| (\\S+)",
Pattern.CASE_INSENSITIVE | Pattern.COMMENTS);
Matcher regexMatcher = regex.matcher(fileContents);
while (regexMatcher.find()) {
if (regexMatcher.start(groupkeyword) >= 0) {
String keyword = regexMatcher.group(groupkeyword).toLowerCase();
if (keyword.equals("table")) {
table = new RECTable();
row = null;
cell = null;
} else if (keyword.equals("row")) {
if (table == null)
throw new Exception("Invalid data: row without table");
row = table.addRow();
cell = null;
} else if (keyword.equals("cell")) {
if (row == null)
throw new Exception("Invalid data: cell without row");
cell = row.addCell();
} else {
throw new Exception("Parser bug: unknown keyword");
}
} else if (regexMatcher.start(groupstring) >= 0) {
String content = regexMatcher.group(groupstring);
content = content.replaceAll("%%", "%");
if (cell != null)
cell.addContent(content);
else if (row != null)
throw new Exception("Invalid data: String after row keyword");
else if (table != null)
table.addCaption(content);
else
throw new Exception("Invalid data: String before table keyword");
} else if (regexMatcher.start(grouperror) >= 0) {
throw new Exception("Invalid data: " +
regexMatcher.group(grouperror));
} else {
throw new Exception("Parser bug: no capturing group matched");
}
}
if (table == null)
throw new Exception("Invalid data: table keyword missing");
return table;
}function importTable(fileContents) {
var table = null;
var row = null;
var cell = null;
var groupkeyword = 1;
var groupstring = 2;
var grouperror = 3;
var myregexp = /\b(table|row|cell)\b|%([^%]*(?:%%[^%]*)*)%|(\S+)/ig;
var match;
var keyword;
var content;
while (match = myregexp.exec(fileContents)) {
if (match[groupkeyword] !== undefined) {
keyword = match[groupkeyword].toLowerCase();
if (keyword == "table") {
table = new RECTable();
row = null;
cell = null;
} else if (keyword == "row") {
if (!table)
throw new Error("Invalid data: row without table");
row = table.addRow();
cell = null;
} else if (keyword == "cell") {
if (!row)
throw new Error("Invalid data: cell without row");
cell = row.addCell();
} else {
throw new Error("Parser bug: unknown keyword");
}
} else if (match[groupstring] !== undefined) {
content = match[groupstring].replace(/%%/g, "%");
if (cell)
cell.addContent(content);
else if (row)
throw new Error("Invalid data: string after row keyword");
else if (table)
table.addCaption(content);
else
throw new Error("Invalid data: string before table keyword");
} else if (match[grouperror] !== undefined) {
throw new Error("Invalid data: " + match[grouperror]);
} else {
throw new Error("Parser bug: no capturing group matched");
}
}
if (!table)
throw new Error("Invalid data: table keyword missing");
return table;
}function importTable(fileContents) {
var table = null;
var row = null;
var cell = null;
var myregexp = XRegExp("(?ix)\\b(?<keyword>table|row|cell)\\b" +
" | %(?<string>[^%]*(?:%%[^%]*)*)%" +
" | (?<error>\\S+)");
XRegExp.forEach(fileContents, myregexp, function(match) {
var keyword;
var content;
if (match.keyword !== undefined) {
keyword = match.keyword.toLowerCase();
if (keyword == "table") {
table = new RECTable();
row = null;
cell = null;
} else if (keyword == "row") {
if (!table)
throw new Error("Invalid data: row without table");
row = table.addRow();
cell = null;
} else if (keyword == "cell") {
if (!row)
throw new Error("Invalid data: cell without row");
cell = row.addCell();
} else {
throw new Error("Parser bug: unknown keyword");
}
} else if (match.string !== undefined) {
content = match.string.replace(/%%/g, "%");
if (cell)
cell.addContent(content);
else if (row)
throw new Error("Invalid data: string after row keyword");
else if (table)
table.addCaption(content);
else
throw new Error("Invalid data: string before table keyword");
} else if (match.error !== undefined) {
throw new Error("Invalid data: " + match.error);
} else {
throw new Error("Parser bug: no capturing group matched");
}
});
if (!table)
throw new Error("Invalid data: table keyword missing");
return table;
}sub importtable {
my $filecontents = shift;
my $table;
my $row;
my $cell;
while ($filecontents =~
m/ \b(table|row|cell)\b
| %([^%]*(?:%%[^%]*)*)%
| (\S+)/ixg) {
if (defined($1)) { # Keyword
my $keyword = lc($1);
if ($keyword eq "table") {
$table = new RECTable();
undef $row;
undef $cell;
} elsif ($keyword eq "row") {
if (!defined($table)) {
die "Invalid data: row without table";
}
$row = $table->addRow();
undef $cell;
} elsif ($keyword eq "cell") {
if (!defined($row)) {
die "Invalid data: cell without row";
}
$cell = $row->addCell();
} else {
die "Parser bug: unknown keyword";
}
} elsif (defined($2)) { # String
my $content = $2;
$content =~ s/%%/%/g;
if (defined($cell)) {
$cell->addContent($content);
} elsif (defined($row)) {
die "Invalid data: string after row keyword";
} elsif (defined($table)) {
$table->addCaption($content);
} else {
die "Invalid data: string before table keyword";
}
} elsif (defined($3)) { # Error
die "Invalid data: $3";
} else {
die "Parser bug: no capturing group matched";
}
}
if (!defined(table)) {
die "Invalid data: table keyword missing";
}
return table;
}def importtable(filecontents):
table = None
row = None
cell = None
for match in re.finditer(
r"""(?ix)\b(?P<keyword>table|row|cell)\b
| %(?P<string>[^%]*(?:%%[^%]*)*)%
| (?P<error>\S+)""", filecontents):
if match.group("keyword") != None:
keyword = match.group("keyword").lower()
if keyword == "table":
table = RECTable()
row = None
cell = None
elif keyword == "row":
if table == None:
raise Exception("Invalid data: row without table")
row = table.addRow()
cell = None
elif keyword == "cell":
if row == None:
raise Exception("Invalid data: cell without row")
cell = row.addCell()
else:
raise Exception("Parser bug: unknown keyword")
elif match.group("string") != None:
content = match.group("string").replace("%%", "%")
if cell != None:
cell.addContent(content)
elif row != None:
raise Exception("Invalid data: string after row keyword")
elif table != None:
table.addCaption(content)
else:
raise Exception("Invalid data: string before table keyword")
elif match.group("error") != None:
raise Exception("Invalid data: " + match.group("error"))
else:
raise Exception("Parser bug: no capturing group matched")
if table == None:
raise Exception("Invalid data: table keyword missing")
return tablefunction importTable($fileContents) {
preg_match_all(
'/ \b(?P<keyword>table|row|cell)\b
| (?P<string>%[^%]*(?:%%[^%]*)*%)
| (?P<error>\S+)/ix',
$fileContents, $matches, PREG_PATTERN_ORDER);
$table = NULL;
$row = NULL;
$cell = NULL;
for ($i = 0; $i < count($matches[0]); $i++) {
if ($matches['keyword'][$i] != NULL) {
$keyword = strtolower($matches['keyword'][$i]);
if ($keyword == "table") {
$table = new RECTable();
$row = NULL;
$cell = NULL;
} elseif ($keyword == "row") {
if ($table == NULL)
throw new Exception("Invalid data: row without table");
$row = $table->addRow();
$cell = NULL;
} elseif ($keyword == "cell") {
if ($row == NULL)
throw new Exception("Invalid data: cell without row");
$cell = $row->addCell();
} else {
throw new Exception("Parser bug: unknown keyword");
}
} elseif ($matches['string'][$i] != NULL) {
$content = $matches['string'][$i];
$content = substr($content, 1, strlen($content)-2);
$content = str_replace('%%', '%', $content);
if ($cell != NULL)
$cell->addContent($content);
elseif ($row != NULL)
throw new Exception("Invalid data: string after row keyword");
elseif ($table != NULL)
$table->addCaption($content);
else
throw new Exception("Invalid data: string before table keyword");
} elseif ($matches['error'][$i] != NULL) {
throw new Exception("Invalid data: " + $matches['error'][$i]);
} else {
throw new Exception("Parser bug: no capturing group matched");
}
}
if ($table == NULL)
throw new Exception("Invalid data: table keyword missing");
return $table;
}def importtable(filecontents)
table = nil
row = nil
cell = nil
groupkeyword = 0;
groupstring = 1;
grouperror = 2;
regexp = / \b(table|row|cell)\b
| %([^%]*(?:%%[^%]*)*)%
| (\S+)/ix
filecontents.scan(regexp) do |match|
if match[groupkeyword]
keyword = match[groupkeyword].downcase
if keyword == "table"
table = RECTable.new()
row = nil
cell = nil
elsif keyword == "row"
if table.nil?
raise "Invalid data: row without table"
end
row = table.addRow()
cell = nil
elsif keyword == "cell"
if row.nil?
raise "Invalid data: cell without row"
end
cell = row.addCell()
else
raise "Parser bug: unknown keyword"
end
elsif not match[groupstring].nil?
content = match[groupstring].gsub("%%", "%")
if not cell.nil?
cell.addContent(content)
elsif not row.nil?
raise "Invalid data: string after row keyword"
elsif not table.nil?
table.addCaption(content)
else
raise "Invalid data: string before table keyword"
end
elsif not match[grouperror].nil?
raise "Invalid data: " + match.group("error")
else
raise "Parser bug: no capturing group matched"
end
end
if table.nil?
raise "Invalid data: table keyword missing"
end
return table
endA straightforward way to create a parser is to use a regular expression to tokenize the input and to use procedural code to parse those tokens.
To tokenize means to scan the file for tokens, which are the smallest elements that the syntax allows. In the file format we’re working with, those tokens are the three keywords, strings enclosed by percentage signs, whitespace between keywords and strings, and nonwhitespace other than keywords and strings. We can easily create a regular expression that matches each of these tokens.
\b(?<keyword>table|row|cell)\b | %(?<string>[^%]*(?:%%[^%]*)*)% | (?<error>\S+)
| Regex options: Free-spacing, case insensitive |
| Regex flavors: .NET, Java 7, XRegExp, PCRE 7, Perl 5.10, Ruby 1.9 |
\b(?P<keyword>table|row|cell)\b | %(?P<string>[^%]*(?:%%[^%]*)*)% | (?P<error>\S+)
| Regex options: Free-spacing, case insensitive |
| Regex flavors: PCRE 4 and later, Perl 5.10, Python |
\b(table|row|cell)\b | %([^%]*(?:%%[^%]*)*)% | (\S+)
| Regex options: Free-spacing, case insensitive |
| Regex flavors: .NET, Java, XRegExp, PCRE, Perl, Python, Ruby |
\b(table|row|cell)\b|%([^%]*+(?:%%[^%]*+)*+)%|(\S+)
| Regex options: Case insensitive |
| Regex flavors: .NET, Java, JavaScript, PCRE, Perl, Python, Ruby |
If you iterate over all the matches of this regular expression in the sample file, it will match each keyword and string separately. On another file with invalid characters, each sequence of invalid characters would also be matched separately. The regular expression does not match the whitespace between keywords and strings because the parser does not need to process it. The word boundaries around the list of keywords are all that is needed to make sure that keywords are delimited with whitespace. We use a separate capturing group for each kind of token. That makes it much easier to identify the token that was matched in the procedural part of our solution.
We use free-spacing and named capture to make our regular expression and our code more readable in the programming languages that have regex flavors that support free-spacing and named capture. There is no functional difference between these four regular expressions.
The capturing group for the strings does not include the
percentage signs that enclose the strings. The benefit is that the
procedural code won’t have to remove those percentage signs to get the
content of the string that was matched. The drawback is that when the
regex matches an empty string (two percentage signs with nothing in
between), the capturing group for the string will find a zero-length
match. When we test which capturing group found the match, we have to
make sure that we accept a zero-length match as a valid match. In the
JavaScript solution, for example, we use if
(match[groupstring] !== undefined), which evaluates to
true if the group participated in the
match attempt, even when the match is empty. We cannot use if (match[groupstring]) because that evaluates
to false when the group finds a
zero-length match.
Internet Explorer 8 and prior do not follow the JavaScript standard that requires nonparticipating groups to be undefined in the match object. IE8 stores empty strings for nonparticipating groups, making it impossible to distinguish between a group that did not participate, and one that participated and captured a zero-length string. This means the JavaScript solution will not work with IE8 and prior. This bug was fixed in Internet Explorer 9.
The XRegExp.exec() method
does return a match object that leaves nonparticipating groups
undefined, regardless of the browser running the code. So does
XRegExp.forEach() as it relies on
XRegExp.exec(). If you need a
solution for browsers such as IE8 that aren’t standards-compliant in
this area, you should use the solution based on XRegExp.
In PHP, the preg_match_all()
function stores NULL in the array for
capturing groups that found a zero-length match as well as for capturing
groups that did not participate in the match. Thus the PHP solution
includes the enclosing percentage signs in the string group. An extra line of PHP code calls
substr to remove them.
The procedural code implements our parser. This parser has four
different states. It keeps track of the state it is in by checking which
of the variables table, row, and cell are assigned.
Nothing: nothing has been read yet. The variables table, row, and cell are all unassigned.
Inside table: a table
keyword has been parsed. The variable table is assigned, while row and cell are unassigned. Since a table can
have any number of caption strings, including none, the parser does
not need a separate state to track whether a string was parsed after
the table keyword.
Inside row: a row keyword
has been parsed. The variables table and row have been assigned, while cell is unassigned.
Inside cell: a cell keyword
has been parsed. The variables table, row, and cell have all been assigned. Since a cell
can have any number of caption strings, including none, the parser
does not need a separate state to track whether a string was parsed
after the cell keyword.
When the parser runs, it iterates over all matches in the regular expression. It checks what kind of token was matched by the regular expression (a keyword, a string, or invalid text) and then processes that token depending on the state the parser is in, as shown in Table 3-2.
Table 3-2. Regex matches are handled depending on the state of the parser
Match | State | |||
|---|---|---|---|---|
Nothing | Inside table | Inside row | Inside cell | |
keyword
| Create new table and change state to “inside table” | Create new table and change state to “inside table” | Create new table and change state to “inside table” | Create new table and change state to “inside table” |
keyword
| Fail: data is invalid | Add row to table and change state to “inside row” | Add row to table | Add row to table and change state to “inside row” |
keyword
| Fail: data is invalid | Fail: data is invalid | Add cell to row and change state to “inside cell” | Add cell to row |
string | Fail: data is invalid | Add caption to table | Fail: data is invalid | Add content to cell |
invalid text | Fail: data is invalid | Fail: data is invalid | Fail: data is invalid | Fail: data is invalid |
Techniques used in the regular expression in this recipe are discussed in Chapter 2. Recipe 2.6 explains word boundaries and Recipe 2.8 explains alternation, which we used to match the keywords. Recipe 2.11 explains named capturing groups. Naming the groups in your regex makes the regex easier to read and maintain.
To match the strings enclosed in percentage signs, we used the same technique explained in Strings for matching quoted strings in source code. The only difference is that here the strings are enclosed with percentage signs rather than quotes.
The parser iterates over all the matches found by the regular expression. Recipe 3.11 explains how that works.