π Regular Expressions: The Pattern Detective
Imagine you have a magical magnifying glass that can find ANY pattern in a giant book instantly. Thatβs what Regular Expressions (RegExp) do for text!
π What Are Regular Expressions?
Think of Regular Expressions like a super-smart search tool.
Simple Example:
- You want to find all phone numbers in a huge document
- Instead of looking one by one, you describe the PATTERN: β10 digitsβ
- The magical tool finds ALL of them in one second!
Real Life:
- When you search for β*.jpgβ to find all pictures = pattern matching
- When a website checks if your email is valid = RegExp
- When your phone highlights phone numbers in messages = RegExp
ποΈ RegExp Creation
There are two ways to create a pattern detector:
Method 1: The Slash Way (Literal)
const pattern = /hello/;
Think of the slashes / like quotation marks, but for patterns!
Method 2: The Constructor Way
const pattern = new RegExp('hello');
Use this when your pattern comes from user input or a variable.
When to Use Which?
Use Slash /pattern/ |
Use new RegExp() |
|---|---|
| Pattern is fixed | Pattern is dynamic |
| You know it beforehand | User types the pattern |
| Faster to write | More flexible |
Example:
// Fixed pattern - use slashes
const findCat = /cat/;
// Dynamic pattern - use constructor
const userSearch = "dog";
const findIt = new RegExp(userSearch);
π§ͺ Test and Exec Methods
These are your two detective tools!
The test() Method - Yes or No Detective
Ask a simple question: βDoes this pattern exist?β
const pattern = /apple/;
pattern.test("I love apples");
// Returns: true β
pattern.test("I love oranges");
// Returns: false β
Think of it like: Asking βIs there a cat in this room?β β Yes or No
The exec() Method - Full Investigation
Get all the details about what you found!
const pattern = /apple/;
const result = pattern.exec("I love apples");
// result[0] = "apple" (what was found)
// result.index = 7 (where it was found)
Think of it like: βFind the cat and tell me WHERE it is and WHAT it looks likeβ
graph TD A[Your Pattern] --> B{Which Method?} B -->|Just need Yes/No| C[test] C --> D[Returns true/false] B -->|Need Details| E[exec] E --> F[Returns match + position]
π© Regular Expression Flags
Flags are like special powers you give to your pattern!
Add them after the closing slash: /pattern/flags
The Main Flags
| Flag | Name | What It Does |
|---|---|---|
g |
Global | Find ALL matches, not just first |
i |
Ignore Case | βAβ and βaβ are the same |
m |
Multiline | ^ and $ work on each line |
Examples:
// Without 'i' flag - case matters
/cat/.test("CAT"); // false β
// With 'i' flag - case ignored
/cat/i.test("CAT"); // true β
// Without 'g' - finds only first
"cat cat cat".match(/cat/);
// ["cat"]
// With 'g' - finds ALL
"cat cat cat".match(/cat/g);
// ["cat", "cat", "cat"]
Memory Trick:
- g = Get all of them
- i = Ignore uppercase/lowercase
- m = Multiple lines matter
π¨ Regular Expression Patterns
Patterns are the descriptions of what youβre looking for!
Simple Patterns
Just type what you want to find:
/hello/ // Finds "hello"
/123/ // Finds "123"
Special Pattern Characters
Some characters have magic powers:
| Character | Meaning | Example |
|---|---|---|
. |
ANY single character | /h.t/ matches βhatβ, βhotβ, βhitβ |
\d |
Any digit (0-9) | /\d\d\d/ matches β123β |
\w |
Any word character | Letters, numbers, underscore |
\s |
Any whitespace | Space, tab, newline |
// Find any 3 digits
/\d\d\d/.test("My code is 789");
// true β
// Find any word
/\w+/.exec("Hello there");
// ["Hello"]
π String Methods with Regex
Strings have special methods that work with patterns!
match() - Find Matches
const text = "I have 3 cats and 2 dogs";
text.match(/\d/g);
// ["3", "2"]
replace() - Find and Replace
const text = "I love cats";
text.replace(/cats/, "dogs");
// "I love dogs"
search() - Find Position
const text = "Hello World";
text.search(/World/);
// 6 (position where "World" starts)
split() - Break Apart
const text = "apple,banana,cherry";
text.split(/,/);
// ["apple", "banana", "cherry"]
graph TD A[String + Pattern] --> B{What do you need?} B -->|Get all matches| C[match] B -->|Swap text| D[replace] B -->|Find position| E[search] B -->|Break into pieces| F[split]
π€ Character Classes
Character classes let you say βmatch ANY of these characters!β
Using Square Brackets [ ]
// Match a, b, OR c
/[abc]/.test("cat"); // true β
/[abc]/.test("dog"); // false β
Ranges with Dash -
// Any lowercase letter
/[a-z]/.test("hello"); // true β
// Any digit
/[0-9]/.test("abc123"); // true β
// Any letter (upper or lower)
/[a-zA-Z]/.test("Hello"); // true β
Negation with ^
Put ^ at the start to mean βNOT theseβ:
// NOT a vowel
/[^aeiou]/.test("b"); // true β
/[^aeiou]/.test("a"); // false β
Built-in Character Classes
| Pattern | Same As | Meaning |
|---|---|---|
\d |
[0-9] |
Any digit |
\D |
[^0-9] |
NOT a digit |
\w |
[a-zA-Z0-9_] |
Word character |
\W |
[^a-zA-Z0-9_] |
NOT word character |
\s |
[ \t\n\r] |
Whitespace |
\S |
[^ \t\n\r] |
NOT whitespace |
π Quantifiers and Anchors
Quantifiers - βHow Many?β
Tell the pattern how many times to match!
| Symbol | Meaning | Example |
|---|---|---|
* |
0 or more | /go*/ matches βgβ, βgoβ, βgoooβ |
+ |
1 or more | /go+/ matches βgoβ, βgoooβ (not βgβ) |
? |
0 or 1 | /colou?r/ matches βcolorβ or βcolourβ |
{n} |
Exactly n | /\d{3}/ matches exactly 3 digits |
{n,} |
n or more | /\d{2,}/ matches 2+ digits |
{n,m} |
n to m | /\d{2,4}/ matches 2 to 4 digits |
// Find words with 2+ o's
/go+d/.test("good"); // true β
/go+d/.test("gd"); // false β
// Phone pattern: 3 digits, dash, 4 digits
/\d{3}-\d{4}/.test("555-1234"); // true β
Anchors - βWhere Exactly?β
Anchors donβt match characters - they match positions!
| Symbol | Position |
|---|---|
^ |
Start of string/line |
$ |
End of string/line |
\b |
Word boundary |
// Must START with "Hello"
/^Hello/.test("Hello World"); // true β
/^Hello/.test("Say Hello"); // false β
// Must END with "World"
/World$/.test("Hello World"); // true β
/World$/.test("World Cup"); // false β
// Complete word only
/\bcat\b/.test("cat"); // true β
/\bcat\b/.test("category"); // false β
π Groups and Capturing
Groups let you bundle patterns together and remember what they matched!
Basic Groups with ( )
// Group "ha" and repeat it
/(ha)+/.test("hahaha"); // true β
// Match "gray" or "grey"
/gr(a|e)y/.test("gray"); // true β
/gr(a|e)y/.test("grey"); // true β
Capturing - Remember What Matched!
Groups automatically save what they matched:
const pattern = /(\d{3})-(\d{4})/;
const result = pattern.exec("555-1234");
// result[0] = "555-1234" (full match)
// result[1] = "555" (first group)
// result[2] = "1234" (second group)
Using Captured Groups in Replace
Use $1, $2, etc. to reference captured groups:
// Swap first and last name
const name = "John Smith";
name.replace(/(\w+) (\w+)/, "$2, $1");
// "Smith, John"
Non-Capturing Groups (?:)
When you need grouping but donβt need to remember:
// Group but don't capture
/(?:ha)+/.test("hahaha"); // true β
// No $1 available - it wasn't captured!
graph TD A[Groups] --> B[Capturing] A --> C[Non-Capturing] B --> D["#40;pattern#41;"] B --> E[Saves to $1, $2...] C --> F["#40;?:pattern#41;"] C --> G[Just for grouping]
π Putting It All Together
Hereβs how all the pieces work together:
// Email validation pattern
const emailPattern = /^[\w.-]+@[\w.-]+\.\w{2,}$/;
// Let's break it down:
// ^ - Start of string
// [\w.-]+ - One or more word chars, dots, or dashes
// @ - Literal @ symbol
// [\w.-]+ - Domain name
// \. - Literal dot (escaped)
// \w{2,} - 2 or more word chars (com, org, etc.)
// $ - End of string
emailPattern.test("user@example.com"); // true β
emailPattern.test("bad@email"); // false β
π― Quick Reference
| Need | Pattern | Example |
|---|---|---|
| Any digit | \d |
"123".match(/\d/g) β [β1β,β2β,β3β] |
| Any letter | [a-zA-Z] |
"Hi5".match(/[a-z]/gi) β [βHβ,βiβ] |
| Start of string | ^ |
/^Hi/.test("Hi there") β true |
| End of string | $ |
/bye$/.test("Good bye") β true |
| One or more | + |
/a+/.test("aaa") β true |
| Zero or more | * |
/ab*c/.test("ac") β true |
| Optional | ? |
/colou?r/.test("color") β true |
| Exact count | {n} |
/\d{4}/.test("2024") β true |
| Group | () |
/(ha)+/.test("haha") β true |
π You Did It!
You now understand:
- β
How to create patterns with
/pattern/ornew RegExp() - β
How to test with
test()and investigate withexec() - β
How flags like
g,i,mgive patterns superpowers - β
How character classes
[abc]match any of several characters - β
How quantifiers
+,*,?,{n}control repetition - β
How anchors
^,$,\bmatch positions - β
How groups
()bundle and capture matches
Regular expressions are like learning a secret code - once you know it, you can find ANY pattern in ANY text instantly! πβ¨