Dev Basics · 6 min read
Regular Expressions: A Beginner's Guide
Regular expressions look intimidating, but they are built from a small set of pieces that combine in predictable ways. Once you know the building blocks, most patterns become readable.
This guide introduces the essentials so you can write and understand everyday regex.
Try it yourself with the related tool.
Test a regular expression →Advertisement
Literal characters and metacharacters
Most characters in a regex match themselves — cat matches the text "cat". A handful are special (metacharacters): . ^ $ * + ? ( ) [ ] { } | \. To match one of these literally, escape it with a backslash, so \. matches a real dot.
Character classes
Square brackets match any one of the characters inside: [aeiou] matches a single vowel. Ranges work too: [a-z] is any lowercase letter, [0-9] any digit. Shorthands help: \d is a digit, \w a word character, \s whitespace.
Quantifiers
Quantifiers say how many times something repeats. * means zero or more, + means one or more, ? means zero or one, and {2,4} means between two and four. So \d{3} matches exactly three digits.
Anchors and groups
Anchors match positions, not characters: ^ is the start of the string and $ is the end. Parentheses create a group you can quantify or capture, so (ab)+ matches "ababab". The best way to learn is to test patterns interactively and watch what they match.
