Skip to content
All tutorials

/tutorials/regular-expressions-a-practical-introduction

Regular Expressions, a Practical Introduction

How to read a regular expression piece by piece, what the most common symbols actually mean, and why testing against real examples beats guessing.

7 min read

Run Regex Tester

A regex is a pattern, not a literal search term

A regular expression describes a pattern that text either matches or does not, rather than a specific string to search for. The pattern \d{3}-\d{4} does not look for that exact text; it looks for any three digits, a hyphen, and four more digits, matching 555-1234 just as readily as 000-0000. Learning to read a handful of core symbols unlocks most of what regex is used for day to day.

The symbols that do most of the work

  • \d, \w, \s: shorthand for any digit, any word character, and any whitespace character.
  • * , + , ?: repeat the previous item zero or more, one or more, or zero or one times.
  • {3} or {2,4}: repeat the previous item an exact number of times, or within a range.
  • [abc]: match any single one of the characters listed inside the brackets.
  • (...) : a capture group, both for grouping a pattern together and for pulling out that specific matched portion afterward.

Repetition is greedy by default

By default, *, + and {} try to match as much text as possible before backing off, which can produce surprising results against text with repeated similar patterns; a pattern like ".*" applied to a string containing two quoted phrases will often match from the first opening quote all the way to the last closing quote, not stop at the first pair. Adding a ? after a repetition symbol makes it lazy instead, matching as little as possible, which is often what people actually intended.

Different languages have slightly different flavors

JavaScript, Python, PHP and other languages all implement regular expressions with small but real differences in supported syntax and behavior. A pattern that works perfectly in one is not guaranteed to behave identically in another, so a pattern tested here, which uses JavaScript's regex engine, should still be sanity checked in whatever language it will actually run in if that differs.

Trying it yourself

Regex Tester runs a pattern against a block of text using your browser's own JavaScript regex engine and highlights every match, including capture groups. Start with something simple like \d+ against a paragraph containing a few numbers, then build up in small steps rather than writing a complex pattern all at once and hoping it works.