Regular Expressions Tutorial for Beginners
Learn regex from scratch with practical examples, common patterns, and debugging techniques.
Introduction to Regular Expressions
Regular expressions (regex or regexp) are powerful patterns used for matching, searching, and manipulating text. They are like a mini programming language specifically designed for text processing.
When to Use Regex
- Validating input (emails, phone numbers, URLs)
- Searching and replacing text patterns
- Parsing structured data
- Extracting information from strings
- Data cleaning and formatting
Basic Pattern Matching
Literal Characters
The simplest regex patterns match exact characters:
Pattern | Matches | Example |
---|---|---|
cat | The word "cat" | "The cat sat" |
123 | The digits "123" | "Room 123" |
Metacharacters and Special Sequences
Metacharacters have special meanings in regex:
Character | Meaning | Example |
---|---|---|
. | Any single character | c.t matches "cat", "cut", "c9t" |
^ | Start of string | ^Hello matches "Hello world" |
$ | End of string | world$ matches "Hello world" |
\d | Any digit (0-9) | \d\d matches "42", "99" |
\w | Word character (a-z, A-Z, 0-9, _) | \w+ matches "hello", "test_123" |
\s | Whitespace character | a\sb matches "a b", "a b" |
Character Classes
Character classes let you match any one of several characters:
[abc] # Matches 'a', 'b', or 'c' [a-z] # Matches any lowercase letter [0-9] # Matches any digit [^abc] # Matches any character except 'a', 'b', or 'c'
Quantifiers
Quantifiers specify how many times a pattern should match:
Basic Quantifiers
- * = 0 or more times
- + = 1 or more times
- ? = 0 or 1 time
- {n} = exactly n times
- {n,} = n or more times
- {n,m} = between n and m times
Examples
a*
matches "", "a", "aaa"a+
matches "a", "aaa" (not "")a?
matches "", "a"a{3}
matches "aaa"a{2,4}
matches "aa", "aaa", "aaaa"
Groups and Capturing
Parentheses create groups that can be captured and reused:
// Capturing groups const pattern = /(\d{3})-(\d{3})-(\d{4})/; const phone = "123-456-7890"; const match = phone.match(pattern); // match[0] = "123-456-7890" (full match) // match[1] = "123" (first group) // match[2] = "456" (second group) // match[3] = "7890" (third group)
Common Regex Patterns
Email Address
^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$
Phone Number (US)
^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$
Password (8+ chars, mixed case, number)
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d@$!%*?&]{8,}$
Using Regex in JavaScript
Creating Regex Patterns
// Literal notation const pattern1 = /hello/i; // i flag = case insensitive // Constructor notation const pattern2 = new RegExp('hello', 'i'); // Dynamic patterns const searchTerm = 'world'; const pattern3 = new RegExp(searchTerm, 'gi');
Common Methods
// test() - returns boolean const pattern = /\d+/; console.log(pattern.test("abc123")); // true // match() - returns match array or null const text = "Contact: 123-456-7890"; const matches = text.match(/\d{3}-\d{3}-\d{4}/); console.log(matches[0]); // "123-456-7890"
Debugging and Testing Regex
Common Regex Pitfalls
- Greedy vs Lazy: Use
.*?
instead of.*
for minimal matching - Escaping: Remember to escape special characters
- Multiline: Use the
m
flag for patterns spanning multiple lines - Performance: Avoid catastrophic backtracking with nested quantifiers
Tips for Writing Better Regex
Start Simple
Build your pattern incrementally. Start with a simple match and add complexity.
Test Thoroughly
Test with edge cases, empty strings, and unexpected inputs.
Consider Alternatives
Sometimes simple string methods are clearer than complex regex.
Conclusion
Regular expressions are incredibly powerful but can be complex. Start with simple patterns and gradually build your skills. Remember that readability matters – a slightly longer but clearer pattern is often better than a clever one-liner.
Practice with Our Regex Tester
Test your regex patterns with our interactive tool featuring real-time matching, syntax highlighting, and common pattern templates.
Open Regex Tester