chapter twelve

12 Wrangling regular expressions

 

This chapter covers

  • A refresher on regular expressions
  • Compiling regular expressions
  • Capturing with regular expressions
  • Working with frequently encountered idioms

Regular expressions are a necessity of modern JavaScript development. Frequently, a half-screen of complex parsing logic can be distilled down to a single regular expression pattern. Regular expressions trivialize the process of tearing apart strings and looking for information.

At the same time, it’s important to understand the limitations of regular expressions. Not all string patterns can be expressed as a (reasonably sized) regular expression. Developers are always tempted to use a regular expression whenever they need to parse a string, whereas a JavaScript Ninja knows when to use a regular expression and when to use a full-fledged parser.

We’ll start with the basics of regular expressions, then touch on advanced features added by the latest ECMAScript specs. Along the way, we’ll look at some alternatives for those complex parsing patterns that regular expressions can’t handle.

12.1 Why regular expressions rock

Let’s say we want to validate that a string, perhaps entered into a form by a website user, follows the format for a nine-digit U.S. postal code. Specifically, the U.S. Postal Service insists that a postal code (also known as a ZIP code) follows this specific format:

ddddd-dddd

12.2 A regular expression refresher

12.2.1 Regular expressions explained

12.2.2 Terms and operators

12.3 Compiling regular expressions

12.4 Capturing matching segments

12.4.1 Performing simple captures

12.4.2 Repeated matching using global expressions

12.4.3 Referencing captures within a regular expression

12.5 String replacement with regexes

12.6 Lookahead, lookbehind, and backtracking

12.6.1 Sneaking a peek with lookahead

12.6.2 Achieving hindsight with lookbehind

12.6.3 Backtracking and regex performance

12.7 Summary