Regular Expressions: A Beginner's Guide

Learn regex from scratch with clear examples and explanations.

basicstutorialbeginner

Regular Expressions Basics

Regular expressions (regex) are patterns for matching text. They're powerful but can be intimidating at first.

Simple Patterns

// Literal match
/hello/ // Matches "hello"

// Case insensitive
/hello/i // Matches "Hello", "HELLO", etc.

// Global (find all)
/hello/g // Finds all occurrences

Character Classes

/[abc]/        // Matches a, b, or c
/[a-z]/ // Matches any lowercase letter
/[A-Z]/ // Matches any uppercase letter
/[0-9]/ // Matches any digit
/[a-zA-Z0-9]/ // Matches any alphanumeric

// Negation
/[^abc]/ // Matches anything EXCEPT a, b, c

Shorthand Classes

\d             // Digit [0-9]
\D // Non-digit [^0-9]
\w // Word char [a-zA-Z0-9_]
\W // Non-word char
\s // Whitespace
\S // Non-whitespace
. // Any character (except newline)

Quantifiers

/a*/           // Zero or more a's
/a+/ // One or more a's
/a?/ // Zero or one a
/a{3}/ // Exactly 3 a's
/a{2,4}/ // 2 to 4 a's
/a{2,}/ // 2 or more a's

Anchors

/^hello/       // Starts with "hello"
/world$/ // Ends with "world"
/^exact$/ // Exactly "exact"
/\bhello\b/ // "hello" as whole word

Common Patterns

// Email (simple)
/^[^\s@]+@[^\s@]+\.[^\s@]+$/

// URL
/https?:\/\/[^\s]+/

// Phone (US)
/\d{3}-\d{3}-\d{4}/

// Date (YYYY-MM-DD)
/\d{4}-\d{2}-\d{2}/

Frequently Asked Questions

Common questions about this topic

Characters like . * + ? [ ] ( ) { } \ ^ $ | have special meanings in regex. To match them literally, escape with backslash: \. matches a period, \* matches an asterisk. In JavaScript strings, double-escape: '\\.' because \ is also a string escape character.

.* is greedy - it matches as much as possible. .*? is lazy/non-greedy - it matches as little as possible. Example: /<.*>/ on '<a><b>' matches '<a><b>' (everything). /<.*?>/ matches '<a>' then '<b>' (minimum each time). Use lazy matching for nested structures.

Add the 'i' flag: /hello/i matches 'Hello', 'HELLO', 'hElLo'. In JavaScript: new RegExp('hello', 'i'). You can combine flags: /hello/gi for global case-insensitive matching. Some patterns need explicit alternatives: /[a-zA-Z]/ matches letters in either case without the flag.