Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 38 ยท Patterns for Text Processing

Extracting Data with Regex

Pull structured data out of free text with regular expressions. Use capture groups, named groups and matchAll to extract emails, hashtags, prices, dates and key-value pairs.

Extraction is the opposite of validation. You do not know where the interesting parts are, and you only want the parts, not the whole text. The tools are capture groups, the g flag and matchAll. The mindset is different too: validators should be strict, extractors should be precise about what they capture but tolerant about what surrounds it.

This lesson works through the typical extraction jobs: lists of simple tokens, numbers with units, and records made of labeled fields. Every example uses named groups so results are self-documenting.

Finding all simple tokens

When you only need the matched text itself, str.match(/pattern/g) returns a plain array of strings (or null if nothing matches, so use ?? []).

Node.js Hashtags, mentions and plain URLs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Pay attention to how the URL pattern ends. A URL in prose is often followed by punctuation (., ,, )), which the pattern above would swallow. A common refinement is to strip trailing punctuation afterwards with .replace(/[.,;:!?)]+$/, "").

Capturing parts with matchAll

matchAll returns an iterator of full match objects, one per match, each with its groups. It requires the g flag. Named groups appear under m.groups.

Node.js Prices with currency and amount

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The decimal part (?:\.\d{1,2})? is optional, so both $2 and $3.50 work. The non-capturing group (?: ) is used because we want to repeat or make optional without creating another capture.

Key-value records

Logs, config files and query strings repeat a key=value pattern. A single global regex can pull all pairs at once, and it can handle quoted values that contain spaces.

Node.js Parsing key=value pairs with quotes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The quoted alternative "(?:[^"\\]|\\.)*" reads: a quote, then any number of either "a character that is not a quote or backslash" or "a backslash and any character", then a closing quote. This is the standard way to handle escapes without lazy .*? tricks, and it is linear.

Dates in several formats

Free text mixes formats. Use an alternation of named groups and normalize afterwards. Because current JavaScript engines support duplicate named groups in different alternatives, one name can serve both formats.

Node.js Normalizing two date formats

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice that 12/04/2025 is ambiguous: day-month or month-day? Regex cannot know. Decide on a convention from the data source and document it.

Extraction guidelines

  • Use word boundaries or look-arounds to avoid partial matches: \b\d{4}\b will not grab part of a 6-digit number, while (?<!\d)\d{4}(?!\d) is stricter still. Lookbehind is not available in every engine.
  • Prefer negated classes ([^"]*) over lazy dots (.*?) when you know the delimiter. They are faster and avoid surprises.
  • Capture only what you need; non-capturing groups for structure.
  • Always handle "no matches": match with g returns null.
  • Post-process: trim punctuation, convert numbers, normalize case.
  • When the text is really structured (HTML, JSON, CSV), use a parser instead. Regex extraction is for loosely structured text.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does "abc".match(/\d+/g) return?

    With the g flag, match returns null when there are no matches, so code should use a fallback like ?? [].
  2. 2. Which method gives you named groups for every match of a global regex?

    matchAll returns an iterator of full match objects, each with its groups. match with g returns only the matched strings.
  3. 3. Why is it good to describe a quoted string body as plain characters or backslash escape pairs?

    Each character is either a normal one or an escape pair, so the engine never needs to guess where the string ends.
  4. 4. When should you avoid regex for extraction?

    Nested formats need parsers. Regex is for flat, loosely structured patterns.

Summary

  • match with g returns an array of strings or null; matchAll returns full match objects.
  • Named groups make extraction readable; non-capturing groups keep structure without extra captures.
  • Negated classes and escape-aware alternations are better than lazy dots for quoted text.
  • Normalize after extracting: dates, numbers, trailing punctuation.
  • Use a real parser for nested or strict formats.

Next: Search and Replace Recipes