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. 3.11. Iterate over All Matches

    Problem

    The previous recipe shows how a regex could be applied repeatedly to a string to get a list of matches. Now you want to iterate over all the matches in your own code.

    Solution

    C#

    You can use the static call when you process only a small number of strings with the same regular expression:

    Match matchResult = Regex.Match(subjectString, @"\d+");
    while (matchResult.Success) {
        // Here you can process the match stored in matchResult
        matchResult = matchResult.NextMatch();
    }

    Construct a Regex object if you want to use the same regular expression with a large number of strings:

    Regex regexObj = new Regex(@"\d+");
    matchResult = regexObj.Match(subjectString);
    while (matchResult.Success) {
        // Here you can process the match stored in matchResult
        matchResult = matchResult.NextMatch();
    }

    VB.NET

    You can use the static call when you process only a small number of strings with the same regular expression:

    Dim MatchResult = Regex.Match(SubjectString, "\d+")
    While MatchResult.Success
        'Here you can process the match stored in MatchResult
        MatchResult = MatchResult.NextMatch
    End While

    Construct a Regex object if you want to use the same regular expression with a large number of strings:

    Dim RegexObj As New Regex("\d+")
    Dim MatchResult = RegexObj.Match(SubjectString)
    While MatchResult.Success
        'Here you can process the match stored in MatchResult
        MatchResult = MatchResult.NextMatch
    End While

    Java

    Pattern regex = Pattern.compile("\\d+");
    Matcher regexMatcher = regex.matcher(subjectString);
    while (regexMatcher.find()) {
        // Here you can process the match stored in regexMatcher
    }

    JavaScript

    If your regular expression may yield a zero-length match, or if you’re simply not sure about that, make sure to work around cross-browser issues dealing with zero-length matches and exec():

    var regex = /\d+/g;
    var match = null;
    while (match = regex.exec(subject)) {
      // Don't let browsers get stuck in an infinite loop
      if (match.index == regex.lastIndex) regex.lastIndex++;
      // Here you can process the match stored in the match variable
    }

    If you know for sure your regex can never find a zero-length match, you can iterate over the regex directly:

    var regex = /\d+/g;
    var match = null;
    while (match = regex.exec(subject)) {
      // Here you can process the match stored in the match variable
    }

    XRegExp

    If you’re using the XRegExp JavaScript library, you can use the dedicated XRegExp.forEach() method to iterate over matches:

    XRegExp.forEach(subject, /\d+/, function(match) {
      // Here you can process the match stored in the match variable
    });

    PHP

    preg_match_all('/\d+/', $subject, $result, PREG_PATTERN_ORDER);
    for ($i = 0; $i < count($result[0]); $i++) {
        # Matched text = $result[0][$i];
    }

    Perl

    while ($subject =~ m/\d+/g) {
        # matched text = $&
    }

    Python

    If you process only a small number of strings with the same regular expression, you can use the global function:

    for matchobj in re.finditer(r"\d+", subject):
        # Here you can process the match stored in the matchobj variable

    To use the same regex repeatedly, use a compiled object:

    reobj = re.compile(r"\d+")
    for matchobj in reobj.finditer(subject):
        # Here you can process the match stored in the matchobj variable

    Ruby

    subject.scan(/\d+/) {|match|
        # Here you can process the match stored in the match variable
    }

    Discussion

    .NET

    Recipe 3.7 explains how to use the Match() member function of the Regex class to retrieve the first regular expression match in the string. To iterate over all matches in the string, we again call the Match() function to retrieve the details of the first match. The Match() function returns an instance of the Match class, which we store in the variable matchResult. If the Success property of the matchResult object holds true, we can begin our loop.

    At the start of the loop, you can use the properties of the Match class to process the details of the first match. Recipe 3.7 explains the Value property, Recipe 3.8 explains the Index and Length properties, and Recipe 3.9 explains the Groups collection.

    When you’re done with the first match, call the NextMatch() member function on the matchResult variable. Match.NextMatch() returns an instance of the Match class, just like Regex.Match() does. The newly returned instance holds the details of the second match.

    Assigning the result from matchResult.NextMatch() to the same matchResult variable makes it easy to iterate over all matches. We have to check matchResult.Success again to see whether NextMatch() did in fact find another match. When NextMatch() fails, it still returns a Match object, but its Success property will be set to false. By using a single matchResult variable, we can combine the initial test for success and the test after the call to NextMatch() into a single while statement.

    Calling NextMatch() does not invalidate the Match object you called it on. If you want, you could keep the full Match object for each regular expression match.

    The NextMatch() method does not accept any parameters. It uses the same regular expression and subject string as you passed to the Regex.Match() method. The Match object keeps references to your regular expression and subject string.

    You can use the static Regex.Match() call, even when your subject string contains a very large number of regex matches. Regex.Match() will compile your regular expression once, and the returned Match object will hold a reference to the compiled regular expression. Match.MatchAgain() uses the previously compiled regular expression referenced by the Match object, even when you used the static Regex.Match() call. You need to instantiate the Regex class only if you want to call Regex.Match() repeatedly (i.e., use the same regex on many strings).

    Java

    Iterating over all the matches in a string is very easy in Java. Simply call the find() method introduced in Recipe 3.7 in a while loop. Each call to find() updates the Matcher object with the details about the match and the starting position for the next match attempt.

    JavaScript

    Before you begin, make sure to specify the /g flag if you want to use your regex in a loop. This flag is explained in Recipe 3.4. while (regexp.exec()) finds all numbers in the subject string when regexp = /\d+/g. If regexp = /\d+/, then while (regexp.exec()) finds the first number in the string again and again, until your script crashes or is forcibly terminated by the browser.

    Note that while (/\d+/g.exec()) (looping over a literal regex with /g) also will get stuck in the same infinite loop, at least with certain JavaScript implementations, because the regular expression is recompiled during each iteration of the while loop. When the regex is recompiled, the starting position for the match attempt is reset to the start of the string. Assign the regular expression to a variable outside the loop, to make sure it is compiled only once.

    Recipes 3.8 and 3.9 explain the object returned by regexp.exec(). This object is the same, regardless of whether you use exec() in a loop. You can do whatever you want with this object.

    The only effect of the /g is that it updates the lastIndex property of the regexp object on which you’re calling exec(). This works even when you’re using a literal regular expression, as shown in the second JavaScript solution for this recipe. Next time you call exec(), the match attempt will begin at lastIndex. If you assign a new value to lastIndex, the match attempt will begin at the position you specified.

    There is, unfortunately, one major problem with lastIndex. If you read the ECMA-262v3 standard for JavaScript literally, then exec() should set lastIndex to the first character after the match. This means that if the match is zero characters long, the next match attempt will begin at the position of the match just found, resulting in an infinite loop.

    All modern browsers implement the standard as written, which means regexp.exec() may get stuck in an infinite loop. This outcome is not unlikely. For example, you can use re = /^.*$/gm; while (re.exec()) to iterate over all lines in a multiline string. If the string has a blank line, your script will get stuck on it.

    The workaround is to increment lastIndex in your own code if the exec() function hasn’t already done this. The first JavaScript solution to this recipe shows you how. If you’re unsure, simply paste in this one line of code and be done with it.

    Older versions of Internet Explorer avoided this problem by incrementing lastIndex by one if the match is zero-length. Internet Explorer 9 only does this when running in quirks mode. This is why Recipe 3.7 claims that you cannot use lastIndex to determine the end of the match, as you’ll get incorrect values in Internet Explorer’s quirks mode.

    All other regular expression engines discussed in this book deal with this by automatically starting the next match attempt one character further in the string, if the previous match was zero-length.

    This problem does not exist with string.replace() (Recipe 3.14) or when finding all matches with string.match() (Recipe 3.10). For these methods, which use lastIndex internally, the ECMA-262v3 standard does state that lastIndex must be incremented for each zero-length match.

    XRegExp

    If you’re using the XRegExp JavaScript library, the dedicated XRegExp.forEach() method makes your life much easier. Pass your subject string, your regular expression, and a callback function to this method. Your callback function will be called for each match of the regular expression in the subject string. The callback will receive the match array, the index of the match (counting from zero), the subject string, and the regex being used to search the string as parameters. If you pass a fourth parameter to XRegExp.forEach(), then this will be used as the context that is used as the value for this in the callback and will also be returned by XRegExp.forEach() after it finishes finding matches.

    XRegExp.forEach() ignores the global and lastIndex properties of the RegExp object you pass to it. It always iterates over all matches. Use XRegExp.forEach() to neatly sidestep any issues with zero-length matches.

    XRegExp also provides its own XRegExp.exec() method. This method ignores the lastIndex property. Instead, it takes an optional third parameter that lets you specify the position at which the match attempt should begin. To find the next match, specify the position where the previous match ended. If the previous match was zero-length, specify the position where the match ended plus one.

    PHP

    The preg_match() function takes an optional fifth parameter to indicate the position in the string at which the match attempt should start. You could adapt Recipe 3.8 to pass $matchstart + $matchlength as the fifth parameter upon the second call to preg_match() to find the second match in the string, and repeat that for the third and following matches until preg_match() returns 0. Recipe 3.18 uses this method.

    In addition to requiring extra code to calculate the starting offset for each match attempt, repeatedly calling preg_match() is inefficient, because there’s no way to store a compiled regular expression in a variable. preg_match() has to look up the compiled regular expression in its cache each time you call it.

    An easier and more efficient solution is to call preg_match_all(), as explained in the previous recipe, and iterate over the array with the match results.

    Perl

    Recipe 3.4 explains that you need to add the /g modifier to enable your regex to find more than one match in the subject string. If you use a global regex in a scalar context, it will try to find the next match, continuing at the end of the previous match. In this recipe, the while statement provides the scalar context. All the special variables, such as $& (explained in Recipe 3.7), are available inside the while loop.

    Python

    The finditer() function in re returns an iterator that you can use to find all the matches of the regular expression. Pass your regular expression as the first parameter and the subject string as the second parameter. You can pass the regular expression options in the optional third parameter.

    The re.finditer() function calls re.compile(), and then calls the finditer() method on the compiled regular expression object. This method has only one required parameter: the subject string.

    The finditer() method takes two optional parameters that the global re.finditer() function does not support. After the subject string, you can pass the character position in the string at which finditer() should begin its search. If you omit this parameter, the iterator will process the whole subject string. If you specify a starting position, you can also specify an ending position. If you don’t specify an ending position, the search runs until the end of the string.

    Ruby

    The scan() method of the String class takes a regular expression as its only parameter and iterates over all the regular expression matches in the string. When it is called with a block, you can process each match as it is found.

    If your regular expression does not contain any capturing groups, specify one iterator variable in the block. This variable will receive a string with the text matched by the regular expression.

    If your regex does contain one or more capturing groups, list one variable for each group. The first variable will receive a string with the text matched by the first capturing group, the second variable receives the second capturing group, and so on. No variable will be filled with the overall regex match. If you want the overall match to be included, enclose your entire regular expression with an extra capturing group.

    subject.scan(/(a)(b)(c)/) {|a, b, c|
        # a, b, and c hold the text matched by the three capturing groups
    }

    If you list fewer variables than there are capturing groups in your regex, you will be able to access only those capturing groups for which you provided variables. If you list more variables than there are capturing groups, the extra variables will be set to nil.

    If you list only one iterator variable and your regex has one or more capturing groups, the variable will be filled with an array of strings. The array will have one string for each capturing group. If there is only one capturing group, the array will have a single element:

    subject.scan(/(a)(b)(c)/) {|abc|
        # abc[0], abc[1], and abc[2] hold the text
        # matched by the three capturing groups
    }

    See Also

    Recipe 3.12 expands on this recipe by only retaining those matches that meet certain criteria.

    Recipe 3.7 shows code to get only the first regex match.

    Recipe 3.8 shows code to determine the position and length of the match.

    Recipe 3.10 shows code to get a list of all the matches a regex can find in a string.

    Construct a Parser shows how you can build a simple parser by iterating over all the matches of a regular expression.