Table of Contents for
Regular Expressions Cookbook, 2nd Edition

Version ebook / Retour

Cover image for bash Cookbook, 2nd Edition Regular Expressions Cookbook, 2nd Edition by Steven Levithan Published by O'Reilly Media, Inc., 2012
  1. Cover
  2. Regular Expressions Cookbook
  3. Preface
  4. Caught in the Snarls of Different Versions
  5. Intended Audience
  6. Technology Covered
  7. Organization of This Book
  8. Conventions Used in This Book
  9. Using Code Examples
  10. Safari® Books Online
  11. How to Contact Us
  12. Acknowledgments
  13. 1. Introduction to Regular Expressions
  14. Regular Expressions Defined
  15. Search and Replace with Regular Expressions
  16. Tools for Working with Regular Expressions
  17. 2. Basic Regular Expression Skills
  18. 2.1. Match Literal Text
  19. 2.2. Match Nonprintable Characters
  20. 2.3. Match One of Many Characters
  21. 2.4. Match Any Character
  22. 2.5. Match Something at the Start and/or the End of a Line
  23. 2.6. Match Whole Words
  24. 2.7. Unicode Code Points, Categories, Blocks, and Scripts
  25. 2.8. Match One of Several Alternatives
  26. 2.9. Group and Capture Parts of the Match
  27. 2.10. Match Previously Matched Text Again
  28. 2.11. Capture and Name Parts of the Match
  29. 2.12. Repeat Part of the Regex a Certain Number of Times
  30. 2.13. Choose Minimal or Maximal Repetition
  31. 2.14. Eliminate Needless Backtracking
  32. 2.15. Prevent Runaway Repetition
  33. 2.16. Test for a Match Without Adding It to the Overall Match
  34. 2.17. Match One of Two Alternatives Based on a Condition
  35. 2.18. Add Comments to a Regular Expression
  36. 2.19. Insert Literal Text into the Replacement Text
  37. 2.20. Insert the Regex Match into the Replacement Text
  38. 2.21. Insert Part of the Regex Match into the Replacement Text
  39. 2.22. Insert Match Context into the Replacement Text
  40. 3. Programming with Regular Expressions
  41. Programming Languages and Regex Flavors
  42. 3.1. Literal Regular Expressions in Source Code
  43. 3.2. Import the Regular Expression Library
  44. 3.3. Create Regular Expression Objects
  45. 3.4. Set Regular Expression Options
  46. 3.5. Test If a Match Can Be Found Within a Subject String
  47. 3.6. Test Whether a Regex Matches the Subject String Entirely
  48. 3.7. Retrieve the Matched Text
  49. 3.8. Determine the Position and Length of the Match
  50. 3.9. Retrieve Part of the Matched Text
  51. 3.10. Retrieve a List of All Matches
  52. 3.11. Iterate over All Matches
  53. 3.12. Validate Matches in Procedural Code
  54. 3.13. Find a Match Within Another Match
  55. 3.14. Replace All Matches
  56. 3.15. Replace Matches Reusing Parts of the Match
  57. 3.16. Replace Matches with Replacements Generated in Code
  58. 3.17. Replace All Matches Within the Matches of Another Regex
  59. 3.18. Replace All Matches Between the Matches of Another Regex
  60. 3.19. Split a String
  61. 3.20. Split a String, Keeping the Regex Matches
  62. 3.21. Search Line by Line
  63. Construct a Parser
  64. 4. Validation and Formatting
  65. 4.1. Validate Email Addresses
  66. 4.2. Validate and Format North American Phone Numbers
  67. 4.3. Validate International Phone Numbers
  68. 4.4. Validate Traditional Date Formats
  69. 4.5. Validate Traditional Date Formats, Excluding Invalid Dates
  70. 4.6. Validate Traditional Time Formats
  71. 4.7. Validate ISO 8601 Dates and Times
  72. 4.8. Limit Input to Alphanumeric Characters
  73. 4.9. Limit the Length of Text
  74. 4.10. Limit the Number of Lines in Text
  75. 4.11. Validate Affirmative Responses
  76. 4.12. Validate Social Security Numbers
  77. 4.13. Validate ISBNs
  78. 4.14. Validate ZIP Codes
  79. 4.15. Validate Canadian Postal Codes
  80. 4.16. Validate U.K. Postcodes
  81. 4.17. Find Addresses with Post Office Boxes
  82. 4.18. Reformat Names From “FirstName LastName” to “LastName, FirstName”
  83. 4.19. Validate Password Complexity
  84. 4.20. Validate Credit Card Numbers
  85. 4.21. European VAT Numbers
  86. 5. Words, Lines, and Special Characters
  87. 5.1. Find a Specific Word
  88. 5.2. Find Any of Multiple Words
  89. 5.3. Find Similar Words
  90. 5.4. Find All Except a Specific Word
  91. 5.5. Find Any Word Not Followed by a Specific Word
  92. 5.6. Find Any Word Not Preceded by a Specific Word
  93. 5.7. Find Words Near Each Other
  94. 5.8. Find Repeated Words
  95. 5.9. Remove Duplicate Lines
  96. 5.10. Match Complete Lines That Contain a Word
  97. 5.11. Match Complete Lines That Do Not Contain a Word
  98. 5.12. Trim Leading and Trailing Whitespace
  99. 5.13. Replace Repeated Whitespace with a Single Space
  100. 5.14. Escape Regular Expression Metacharacters
  101. 6. Numbers
  102. 6.1. Integer Numbers
  103. 6.2. Hexadecimal Numbers
  104. 6.3. Binary Numbers
  105. 6.4. Octal Numbers
  106. 6.5. Decimal Numbers
  107. 6.6. Strip Leading Zeros
  108. 6.7. Numbers Within a Certain Range
  109. 6.8. Hexadecimal Numbers Within a Certain Range
  110. 6.9. Integer Numbers with Separators
  111. 6.10. Floating-Point Numbers
  112. 6.11. Numbers with Thousand Separators
  113. 6.12. Add Thousand Separators to Numbers
  114. 6.13. Roman Numerals
  115. 7. Source Code and Log Files
  116. Keywords
  117. Identifiers
  118. Numeric Constants
  119. Operators
  120. Single-Line Comments
  121. Multiline Comments
  122. All Comments
  123. Strings
  124. Strings with Escapes
  125. Regex Literals
  126. Here Documents
  127. Common Log Format
  128. Combined Log Format
  129. Broken Links Reported in Web Logs
  130. 8. URLs, Paths, and Internet Addresses
  131. 8.1. Validating URLs
  132. 8.2. Finding URLs Within Full Text
  133. 8.3. Finding Quoted URLs in Full Text
  134. 8.4. Finding URLs with Parentheses in Full Text
  135. 8.5. Turn URLs into Links
  136. 8.6. Validating URNs
  137. 8.7. Validating Generic URLs
  138. 8.8. Extracting the Scheme from a URL
  139. 8.9. Extracting the User from a URL
  140. 8.10. Extracting the Host from a URL
  141. 8.11. Extracting the Port from a URL
  142. 8.12. Extracting the Path from a URL
  143. 8.13. Extracting the Query from a URL
  144. 8.14. Extracting the Fragment from a URL
  145. 8.15. Validating Domain Names
  146. 8.16. Matching IPv4 Addresses
  147. 8.17. Matching IPv6 Addresses
  148. 8.18. Validate Windows Paths
  149. 8.19. Split Windows Paths into Their Parts
  150. 8.20. Extract the Drive Letter from a Windows Path
  151. 8.21. Extract the Server and Share from a UNC Path
  152. 8.22. Extract the Folder from a Windows Path
  153. 8.23. Extract the Filename from a Windows Path
  154. 8.24. Extract the File Extension from a Windows Path
  155. 8.25. Strip Invalid Characters from Filenames
  156. 9. Markup and Data Formats
  157. Processing Markup and Data Formats with Regular Expressions
  158. 9.1. Find XML-Style Tags
  159. 9.2. Replace Tags with
  160. 9.3. Remove All XML-Style Tags Except and
  161. 9.4. Match XML Names
  162. 9.5. Convert Plain Text to HTML by Adding

    and
    Tags

  163. 9.6. Decode XML Entities
  164. 9.7. Find a Specific Attribute in XML-Style Tags
  165. 9.8. Add a cellspacing Attribute to Tags That Do Not Already Include It
  166. 9.9. Remove XML-Style Comments
  167. 9.10. Find Words Within XML-Style Comments
  168. 9.11. Change the Delimiter Used in CSV Files
  169. 9.12. Extract CSV Fields from a Specific Column
  170. 9.13. Match INI Section Headers
  171. 9.14. Match INI Section Blocks
  172. 9.15. Match INI Name-Value Pairs
  173. Index
  174. Index
  175. Index
  176. Index
  177. Index
  178. Index
  179. Index
  180. Index
  181. Index
  182. Index
  183. Index
  184. Index
  185. Index
  186. Index
  187. Index
  188. Index
  189. Index
  190. Index
  191. Index
  192. Index
  193. Index
  194. Index
  195. Index
  196. Index
  197. Index
  198. Index
  199. About the Authors
  200. Colophon
  201. Copyright
  202. Construct a Parser

    Problem

    You have an application that stores certain data in a table. Your task is to add a new feature to this application to import that data from a file format that your application does not yet support. There are no off-the-shelf parsers available for this file format. You will have to roll your own.

    The rules of the file format you need to parse are as follows:

    1. The keyword table begins a new table. A file can have an unlimited number of tables, and must have at least one.

    2. Any strings that follow the table keyword form the table’s caption. A table does not need to have a caption.

    3. The keyword row begins a new row. A row cannot exist outside of a table. A table can have an unlimited number of rows, and must have at least one.

    4. The row keyword cannot be followed by a string.

    5. The keyword cell begins a new cell. A cell cannot exist outside of a row. A row can have an unlimited number of cells, but does not need any. Different rows in the same table can have different numbers of cells.

    6. Any strings that follow the cell keyword form the content of the cell. A cell does not need to have any content.

    7. A string is a sequence of zero or more characters enclosed by percentage signs. A string with nothing between the percentage signs is an empty string. Two sequential percentage signs in a character string denote a single character, a percentage sign. No characters other than the percentage sign have a special meaning in strings. Line breaks and other control characters that appear between the percentage signs are all part of the string.

    8. If two or more strings follow the same table or cell keyword, those strings form separate lines in the table’s caption or the cell’s content, regardless of whether there is a line break between the strings in the file.

    9. Keywords are case insensitive. Cell, cell, CELL, and CeLl are all the same.

    10. Any whitespace between keywords and/or strings must be ignored. Whitespace is required to delimit adjacent keywords. Whitespace is also required to delimit adjacent strings. Whitespace is not required to delimit keywords from strings.

    11. Any characters in the file that do not form a keyword or string are an error.

    This sample file illustrates the rules:

    table %First table%
      row cell %A1% cell %B1% cell%C1%cell%D1%
      ROW row CELL %The previous row was blank%
      cell %B3%
      row
        cell %A4% %second line%
        cEll %B4%
             %second line%
        cell %C4
    second line%
      row cell %%%string%%%
        cell %%
        cell %%%%
        cell %%%%%%

    Formatted as a table, it would look like Table 3-1.

    Table 3-1. Table to be parsed from the sample file

    A1

    B1

    C1

    D1

    (omitted)

    (omitted)

    (omitted)

    (omitted)

    The previous row was blank

    B3

    (omitted)

    (omitted)

    A4
    second line

    B4
    second line

    C4
    second line

    (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.

Solution

C#

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;
}

VB.NET

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 Function

Java

RECTable 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;
}

JavaScript

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;
}

XRegExp

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;
}

Perl

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;
}

Python

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 table

PHP

function 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;
}

Ruby

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
end

Discussion

A 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.

Caution

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.

  1. Nothing: nothing has been read yet. The variables table, row, and cell are all unassigned.

  2. 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.

  3. Inside row: a row keyword has been parsed. The variables table and row have been assigned, while cell is unassigned.

  4. 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 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”

Create new table and change state to “inside table”

keyword row

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 cell

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

See Also

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.