Regular Expressions: A Practical Beginner’s Guide

A regular expression describes a text pattern. Start with a sample whose matches you can identify by hand. Add one constraint at a time and keep examples that should fail alongside examples that should match.

Extract numeric IDs from a log fixture

Start with the literal Order # prefix. Add a digit pattern and a plus quantifier for one or more digits. Wrap it in a named group so the caller can read the ID directly. The global flag allows matchAll to iterate across both matching lines.

In the Regex Tester’s pattern field, enter the pattern without JavaScript’s surrounding slashes and put g in the Flags field. Include Order #oops as a negative case. If you need to match an entire line, add anchors and use the multiline flag when testing several lines together.

JavaScript
const text = "Order #402\nOrder #oops\nOrder #1138";
const ids = [...text.matchAll(/Order #(?<id>\d+)/g)]
  .map((match) => match.groups.id);
console.log(ids.join(", "));
Result
402, 1138

Understand anchors, flags and escaping

By default, caret and dollar apply to the input boundaries. With m they also match line boundaries. The s flag changes whether a dot can match a newline. Use flags based on the problem instead of adding them all.

The pattern string passed to new RegExp needs JavaScript string escaping. A backslash that belongs to the pattern must survive the string parser. Similarly, a literal dot in the data needs a regex escape, because an unescaped dot matches many characters.

Keep failures and runtime costs easy to diagnose

When a pattern matches too much, add examples with trailing junk, repeated delimiters or missing fields. If it matches too little, remove constraints until you locate the failing assumption. Check offsets in UTF-16 units when working with emoji and JavaScript string slicing.

Broad, nested quantifiers can make failing matches expensive. Use precise character classes and avoid overlapping repeated alternatives when possible. The browser tester limits execution time and results. Repeat your final test in the language and engine you will deploy.

Frequently asked questions

Will the same expression work in Python?
Some patterns do, but named groups, flags and Unicode behavior can differ by engine.
Should I parse JSON with regex?
Use a JSON parser for structured data. Regex is useful for extracting fields from simple text formats or doing a preliminary check.

Try it with these tools

Related developer guides