Regular Expressions

Loading concept...

πŸ” 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/ or new RegExp()
  • βœ… How to test with test() and investigate with exec()
  • βœ… How flags like g, i, m give patterns superpowers
  • βœ… How character classes [abc] match any of several characters
  • βœ… How quantifiers +, *, ?, {n} control repetition
  • βœ… How anchors ^, $, \b match 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! πŸ”βœ¨

Loading story...

No Story Available

This concept doesn't have a story yet.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

Interactive Preview

Interactive - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Interactive Content

This concept doesn't have interactive content yet.

Cheatsheet Preview

Cheatsheet - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Cheatsheet Available

This concept doesn't have a cheatsheet yet.

Quiz Preview

Quiz - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Quiz Available

This concept doesn't have a quiz yet.