Regular Expressions (Regex) for Beginners

A regular expression (regex) is a compact pattern that describes a set of strings. One expression can find every email address in a log, validate a phone number field, extract the order id from a URL or rename a thousand files at once. Every major language — JavaScript, Python, Java, Go, C#, PHP — and every editor and command-line tool understands the same core syntax.

This guide teaches that core: literal characters, character classes, quantifiers, anchors, groups and flags — with a cheat sheet, patterns you can copy, and the mistakes that make a regex match too much or too little.

Literal characters and metacharacters

Most characters match themselves: the pattern cat matches "cat" inside "concatenate". Twelve characters are special and must be escaped with a backslash to be matched literally: . ^ $ * + ? ( ) [ ] { } | \ and /. The dot is the one that bites — a.b matches "a" followed by any character then "b", so "a.b" also matches "aXb".

colou?r       matches "color" and "colour"
\d{3}-\d{4}   matches 555-1234
\.            matches a literal dot
https?://     matches http:// and https://

Try it: Regex Tester

Character classes

  • [abc] — one of a, b or c. [a-z] — any lower-case letter. [^0-9] — anything except a digit.
  • \d — a digit [0-9]. \w — a word character [A-Za-z0-9_]. \s — whitespace (space, tab, newline). Upper case negates: \D, \W, \S.
  • . — any character except a newline (unless the s flag is set).
  • Unicode — in JavaScript use the u flag and \p{L} for any letter, \p{Script=Arabic} for Arabic, \p{Script=Devanagari} for Hindi. Without it, \w matches only ASCII.

Quantifiers: how many times

  • * — zero or more. + — one or more. ? — zero or one.
  • {3} — exactly three. {2,5} — two to five. {2,} — two or more.
  • Quantifiers are greedy: .* takes as much as possible. Add ? to make them lazy: .*? stops at the first chance. <.+> on "<a><b>" matches the whole string; <.+?> matches "<a>".

Try it: Regex Explainer

Anchors, groups and alternation

  • ^ — start of the string (or line with the m flag). $ — end. \b — a word boundary, so \bcat\b matches "cat" but not "concatenate".
  • ( ) — a capturing group: (\d{4})-(\d{2}) captures the year and month separately. (?: ) groups without capturing. (?<year>\d{4}) names the group.
  • | — alternation: jpg|png|gif matches any of the three. Wrap it in a group to limit its scope: \.(jpg|png|gif)$.
  • (?=…) and (?!…) — lookahead: match only if what follows does (or does not) match, without consuming it. Used for password rules: ^(?=.*\d)(?=.*[A-Z]).{12,}$.

Flags

  • i — case-insensitive. g — global (find all matches, not just the first). m — multiline: ^ and $ match at line boundaries.
  • s — dotall: . also matches newlines. u — Unicode mode. x (some engines) — ignore whitespace and allow comments in the pattern.

Patterns you can copy

Email (practical):    ^[^\s@]+@[^\s@]+\.[^\s@]{2,}$
Saudi mobile:         ^(?:\+966|0)5\d{8}$
Indian mobile:        ^(?:\+91|0)?[6-9]\d{9}$
ISO date:             ^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$
UUID:                 ^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$
URL (loose):          ^https?://[^\s/$.?#].[^\s]*$
Hex color:            ^#(?:[0-9a-fA-F]{3}){1,2}$
Strong password:      ^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^\w\s]).{12,}$
Trim whitespace:      ^\s+|\s+$
Extract order id:     /orders/(\d+)

Try it: Regex Tester Try it: Regex Generator

Mistakes that match too much or too little

  • Forgetting anchors: \d{4} "validates" 12345 because it finds 1234 inside it. Use ^\d{4}$.
  • Unescaped dots: example.com matches "exampleXcom". Write example\.com.
  • Greedy quantifiers across the whole line: "(.*)" on a line with two quoted strings captures both.
  • Catastrophic backtracking: nested quantifiers like (a+)+ on a non-matching input can take seconds or hang. Keep quantifiers simple and test with long inputs.
  • Validating email with a giant pattern: the practical pattern above plus a confirmation email beats a 400-character regex that still rejects valid addresses.
  • Locale assumptions: \w does not match Arabic or Devanagari letters without Unicode mode.

Try it: Regex Tester Try it: Regex Explainer

Frequently asked questions

What is a regular expression used for?

Finding, validating, extracting and replacing text that follows a pattern: form validation, log searching, parsing ids out of strings, bulk renaming and editor search-and-replace.

What does \d mean in regex?

Any single digit, 0–9. \d{3} means exactly three digits; \d+ means one or more.

What is the difference between * and + in regex?

* matches zero or more repetitions (so the element may be absent); + requires at least one.

Is regex the same in every language?

The core syntax is shared, but details differ: lookbehind support, named groups, Unicode classes and flags vary between JavaScript, Python (re), Java, PCRE (PHP) and Go (RE2, which has no backtracking).

How do I test a regex?

Paste the pattern and sample text into a tester that highlights matches and groups, then try inputs that should not match. Include long and unusual inputs to catch performance problems.

Can I use regex to parse HTML or JSON?

For a quick one-off extraction, yes. For anything reliable, no — nested structures need a real parser. Use a JSON tree viewer or JSONPath for JSON.

Tools mentioned in this guide

Test regular expressions live with match highlighting, capture groups and replace preview.

Utilities Open tool

Build regular expressions from a library of tested patterns (email, URL, IP, dates, IBAN, Saudi/Jordan phone numbers…) and custom rules.

Utilities Open tool

Compare two texts line by line or word by word and highlight differences.

Formatting Open tool

Evaluate JSONPath expressions ($.store.book[*].author) against JSON and see matches live.

JSON & Data Open tool

More guides

More guides →