What Regular Expressions Are
You'll learn what regular expressions are and when to use them instead of simple string methods.
The Core Idea
Regular expressions (often shortened to "regex" or "regexp") are patterns used to match, search, and manipulate text. Think of them as a specialized mini-language for describing what text should look like, rather than what it exactly is.
Imagine you're looking for a phone number in a document. With string methods, you'd need to know the exact phone number: "555-1234". But with regex, you can describe the pattern: "three digits, a dash, four digits" — and find any phone number matching that structure.
When to Use Regex vs String Methods
Use string methods (includes(), startsWith(), indexOf(), etc.) when:
- You know the exact text you're looking for
- You need simple, readable checks
- Performance is critical for simple operations
Use regex when:
- You need to match patterns (like "any email address")
- You want flexible matching (case-insensitive, wildcards)
- You need to validate formats (dates, phone numbers, URLs)
- You're extracting or replacing complex patterns
The Power and the Cost
Regex is incredibly powerful but comes with tradeoffs. It uses a special syntax that can look cryptic at first. A regex to match an email might look like /\w+@\w+\.\w+/ — not exactly beginner-friendly! But once learned, regex can solve in one line what might take dozens of lines with string methods.
Key Takeaway: Regular expressions are pattern-matching tools that describe text structure rather than exact content — use them for complex text operations, but stick to string methods for simple exact matches.