Skip to content

Chapter 7 of 8

Practical Recipes for Validation and Extraction

Real-world regex patterns solve recurring problems in input validation and text extraction. For an IPv4 address, each octet must lie in the range 0 to 255, which is most cleanly written as the alternation (25[0-5]|2[0-4]\d|[01]?\d\d?), repeated four times with literal dots between them and anchored at both ends. A practical email validator is the deceptively simple ^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$, which catches the vast majority of real addresses; the RFC 5321/5322 grammar is far more permissive and cannot be reliably enforced by a single regex, so production systems should always send a confirmation email. A URL pattern typically starts with https?://[^\s/$.?#].[^\s]*, which enforces the scheme and forbids whitespace and common URL delimiters in the host portion.

Date and number validation patterns encode well-known numeric ranges. A date in YYYY-MM-DD form is matched by ^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])\(, which enforces a four-digit year, months 01-12, and days 01-31, although it does not check months with fewer than 31 days or leap years. A 24-hour time is ^([01]\d|2[0-3]):[0-5]\d\), with hours constrained to 00-19 or 20-23 and minutes to 00-59. A US zip code with an optional 4-digit extension is ^\d{5}(?:-\d{4})?\(. A positive integer without leading zeros is ^[1-9]\d*\), while a floating-point number with an optional sign and fraction is ^-?\d+(\.\d+)?$; scientific notation can be added with ([eE][+-]?\d+)?.

Several extraction patterns appear in nearly every codebase. A hexadecimal color code is matched by ^#([0-9A-Fa-f]{3}){1,2}$, with the eight-digit form including alpha handled by an additional optional group (?:[0-9a-fA-F]{2})?. A UUID v4 is identified by its 8-4-4-4-12 grouping with a version nibble of 4 and a variant nibble in [89ab]: ^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$. To capture the area code from a US phone number like (555) 123-4567, escape the parentheses and write \((\d{3})\)\s*(\d{3})-(\d{4}), producing three captured groups. The body of an HTML <script> tag can be extracted with <script\b[^>]*>([\s\S]*?)</script>, where [\s\S] is a common trick to match any character including newlines without enabling the dotall flag.

Before embedding a regex in production, remember two practical rules. First, never embed raw user input as a regex without escaping metacharacters; use re.escape in Python, Pattern.quote in Java, or the manual replacement str.replace(/[.*+?^\({}()|[\]\\]/g, '\\\)&') in JavaScript. Second, regex is the wrong tool for parsing HTML for security or correctness; even the strip-tags pattern <[^>]+> fails on malformed HTML, comments, and CDATA sections, so prefer a proper sanitizer like DOMPurify for any user-facing context.

All chapters
  1. 1Character Matching: Metacharacters, Shorthands, and Classes
  2. 2Quantifiers: Greedy, Lazy, Possessive, and Exact
  3. 3Anchors and Boundaries
  4. 4Groups, Captures, and Backreferences
  5. 5Lookaround Assertions
  6. 6Flags, Modes, and Engine Features
  7. 7Practical Recipes for Validation and Extraction
  8. 8Performance and Engine Internals

Drill it

Reading is not remembering. These come from the Regex Patterns Every Developer Should Know deck:

Q

What does the regex metacharacter <code>.</code> match by default?

A single character of any kind except the newline character (\n). To make it also match newlines, use the s (dotall / single-line) flag, e.g. /foo.bar/s in Java...

Q

Which character class matches any single digit in most regex flavors?

[0-9] or the shorthand \d. \d is equivalent to [0-9] in ASCII; with Unicode (u flag in JS, default in Python 3 str) it matches any Unicode decimal digit, e.g. A...

Q

What does the shorthand <code>\w</code> match?

Any word character. In ASCII mode this is [A-Za-z0-9_]; in Unicode mode it also matches letters and digits from other scripts, and the underscore.

Q

What does the shorthand <code>\s</code> match?

Any whitespace character: space, tab (\t), newline (\n), carriage return (\r), form feed (\f), and vertical tab (\v). In Unicode mode it can also match rare whi...