Utility Hub
DeveloperUpdated

Regular Expressions Explained for Beginners

A beginner's guide to regular expressions — what they are, how the syntax works, and practical examples using JavaScript-compatible patterns.

RegexRegular ExpressionsDeveloper Tools

What is a regular expression?

A regular expression (often shortened to regex or regexp) is a pattern that describes a set of strings. Give a regex engine some text and a pattern, and it tells you whether the pattern appears in the text — and where.

Regex is built into virtually every programming language and many text editors. It is used for searching, validation, extraction, and substitution. The syntax looks cryptic at first, but it follows consistent rules.

Literals

The simplest regex is a literal string. The pattern cat matches the sequence of characters c, a, t wherever it appears:

Text:    "The cat sat on the mat."
Pattern: cat
Match:   "The [cat] sat on the mat."

Regex is case-sensitive by default. cat does not match Cat unless you use the case-insensitive flag.

Character classes

A character class matches one character from a set. You define the set inside square brackets [ ].

PatternMatches
[aeiou]Any single vowel
[0-9]Any single digit
[a-z]Any lowercase letter
[A-Za-z]Any letter (upper or lower)
[^aeiou]Any character that is not a vowel

Ranges work within a character class: [a-z] matches any character from a to z.

Shorthand character classes — these are built-in shortcuts:

ShorthandEquivalentMeaning
\d[0-9]Any digit
\D[^0-9]Any non-digit
\w[A-Za-z0-9_]Any word character (alphanumeric and underscore)
\W[^A-Za-z0-9_]Any non-word character
\s[ \t\n\r]Any whitespace character
\S[^ \t\n\r]Any non-whitespace character

The dot (.) metacharacter and escaping:

The dot . is a special metacharacter. In standard JavaScript regular expressions, it matches any single character except line terminators (such as \n or \r), unless the s ("dotAll") flag is active.

Because the dot has this special wildcard meaning, matching a literal period (such as in a decimal number, URL, or file extension) requires escaping it with a backslash: \..

Quantifiers

Quantifiers specify how many times the preceding element must appear.

QuantifierMeaning
?Zero or one time (optional)
*Zero or more times
+One or more times
{n}Exactly n times
{n,}At least n times
{n,m}Between n and m times

Examples:

\d+       matches one or more digits: "42", "007", "1"
\d{4}     matches exactly four digits: "2024"
colou?r   matches "color" and "colour" (the 'u' is optional)

By default, quantifiers are greedy — they match as much as possible. Add ? after a quantifier to make it lazy (match as little as possible): .*? vs .*.

Anchors

Anchors do not match characters — they match positions in the string.

AnchorMatches
^Start of the string (or start of a line in multiline mode)
$End of the string (or end of a line in multiline mode)
\bA word boundary — the position between a word character and a non-word character
^Hello    matches "Hello" only at the start of the string
world$    matches "world" only at the end of the string
\bcat\b   matches "cat" as a whole word, not "scattered" or "concatenate"

Groups

Parentheses () create a capturing group — they group part of the pattern and capture the matched text for later use.

(\d{4})-(\d{2})-(\d{2})

This matches a date like "2024-03-15" and captures the year, month, and day as three separate groups.

Non-capturing groups use (?:...) — they group without capturing:

(?:https?|ftp)://

This matches http://, https://, or ftp:// without creating a capture group.

Alternation (|) inside a group works like OR:

gr(a|e)y    matches "gray" and "grey"

Flags

Flags modify how the pattern is applied. In JavaScript, they are appended after the closing slash of a regex literal.

FlagDescription
iCase-insensitive matching
gGlobal — find all matches, not just the first
mMultiline — ^ and $ match line starts/ends
sDotall — . matches newline characters too
// JavaScript examples
/cat/i        // matches "cat", "Cat", "CAT"
/\d+/g        // find all numbers in the string
/^start/m     // match "start" at the beginning of any line

Building a pattern step by step

Rather than memorizing long, complex expressions, the best way to write regular expressions is to construct them incrementally. Consider a common real-world task: validating a username.

Suppose an application requires usernames to follow these rules:

  1. Must start with a lowercase letter.
  2. May contain only lowercase letters, digits, and underscores.
  3. Must be between 3 and 16 characters in total length.

Here is how to build that pattern step by step:

Step 1: Match the required starting character

We want the first character to be a letter from a to z. We define a character class:

[a-z]

Step 2: Match the remaining allowed characters

Subsequent characters can be lowercase letters, digits, or underscores:

[a-z0-9_]

Step 3: Enforce total length with a quantifier

The first character is already handled by Step 1. To reach a total length of 3 to 16 characters, we need between 2 and 15 additional characters. We append the range quantifier {2,15}:

[a-z][a-z0-9_]{2,15}

Step 4: Lock the boundaries with anchors

Without anchors, our pattern would find a match inside invalid strings like "@@alice_99@@". To ensure the entire input matches from start to finish, we wrap the pattern in anchors (^ and $):

^[a-z][a-z0-9_]{2,15}$

Now our pattern behaves predictably:


How to test and debug regex

Regular expressions are dense, and subtle bugs are common. Use these practical habits when testing:

  1. Test positive and negative cases: Always test your pattern with inputs that should match and inputs that should fail (such as empty strings, spaces, and boundary lengths).
  2. Check for missing anchors: If an expression unexpectedly accepts invalid input, verify whether ^ or $ is missing. Without anchors, regex matches substrings anywhere in the text.
  3. Use an interactive tester: Paste your pattern into our interactive Regex Tester to inspect matches, test flags, and highlight capture groups live.

For a ready-to-use reference catalog covering emails, phone numbers, URLs, dates, and IPv4 addresses, see our companion guide: Common Regex Patterns and Examples.

Technical Review & Privacy Commitment

Content on Utility Hub is written by software engineers and cross-referenced with official specifications (RFC, W3C, IEEE). All calculations and text processing execute 100% locally in your browser with zero server data collection.