Regular Expressions

📖 Concept

Regular expressions (regex) are patterns used to match character combinations in strings. They can look intimidating but are incredibly powerful for validation, search, and text processing.

Creating: /pattern/flags or new RegExp("pattern", "flags") Flags: g (global), i (case-insensitive), m (multiline), s (dotAll), u (unicode) Key methods: test(), match(), matchAll(), replace(), search(), split()

🏠 Real-world analogy: Regex is like a metal detector with adjustable sensitivity — you define the pattern (metal type), and it scans text to find all matches.

💻 Code Example

codeTap to expand ⛶
1// Basic patterns
2const emailRegex = /^[\w.-]+@[\w.-]+\.\w{2,}$/i;
3console.log(emailRegex.test("user@example.com")); // true
4
5// Common patterns
6const phoneRegex = /^\+?\d{1,3}[-.\s]?\d{3,4}[-.\s]?\d{4}$/;
7const urlRegex = /^https?:\/\/[\w.-]+\.[a-z]{2,}/i;
8const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/;
9
10// Methods
11const str = "Hello World hello world";
12console.log(str.match(/hello/gi)); // ["Hello", "hello"]
13console.log(str.replace(/world/gi, "JS")); // "Hello JS hello JS"
14console.log(str.search(/world/i)); // 6
15
16// Groups and captures
17const date = "2024-01-15";
18const [, year, month, day] = date.match(/(\d{4})-(\d{2})-(\d{2})/);
19console.log({ year, month, day });
20
21// Named groups
22const dateMatch = date.match(/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/);
23console.log(dateMatch.groups); // { year: "2024", month: "01", day: "15" }
24
25// Lookahead and lookbehind
26const prices = "Item: $100, Tax: $15, Total: $115";
27const amounts = prices.match(/(?<=\$)\d+/g); // ["100", "15", "115"]

🏋️ Practice Exercise

Mini Exercise:

  1. Write a regex to validate email addresses
  2. Write a regex to extract all hashtags from a tweet
  3. Create a function that converts camelCase to kebab-case
  4. Write a password strength validator using regex

⚠️ Common Mistakes

  • Forgetting to escape special characters: . matches ANY character, use \. for a literal dot

  • Using greedy quantifiers (.*) when lazy (.*?) is needed — greedy matches too much

  • Not using the g flag when you need all matches, not just the first

  • Forgetting that ^ and $ match start/end of string, not line (unless m flag is used)

  • Complex regex is hard to maintain — consider splitting into multiple simpler checks or use named groups

💼 Interview Questions

🎤 Mock Interview

Mock interview is powered by AI for Regular Expressions. Login to unlock this feature.