Topic 40 of 87
Regex Basics
Overview
Regular Expressions (Regex) are intricate patterns used to match character combinations in strings. They are extremely powerful for advanced string searching, complex validation (like emails and phone numbers), and global replacements.
While Regex looks like gibberish to beginners, understanding the basic flags and methods is crucial for passing technical interviews.
Syntax
Regex Syntax and Flags
javascript
const text = "Visit Microsoft! Microsoft is big.";
// Syntax: /pattern/flags
// 'i' flag means case-Insensitive
const res1 = text.replace(/microsoft/i, "W3Schools");
// "Visit W3Schools! Microsoft is big."
// 'g' flag means Global (replace ALL instances)
const res2 = text.replace(/Microsoft/g, "Apple");
// "Visit Apple! Apple is big."
// Combine flags!
const res3 = text.replace(/microsoft/ig, "Apple");Testing Strings
javascript
// Pattern: must contain only letters (a-z)
const lettersRegex = /^[a-zA-Z]+$/;
// .test() returns a boolean
console.log(lettersRegex.test("Hello")); // true
console.log(lettersRegex.test("Hello 123")); // falseCommon Pitfalls
- Trying to memorize complex Regex patterns (like the official RFC 5322 email regex). In the real world, developers copy-paste complex regex from libraries. Interviewers usually only expect you to know basic flags (
/i,/g) and simple patterns like/^[0-9]+$/.
Interview Questions
Q:
What does the
/g flag do in a regular expression?A:
The /g (global) flag tells the Regex engine to find all matches in a string, rather than stopping after the first match is found.
Real-World Example
Validating that a user's password contains at least one number and one special character before allowing them to sign up.
example
javascript
const passwordRegex = /^(?=.*[0-9])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{8,}$/;
if (!passwordRegex.test(userInput)) {
alert("Weak password");
}Check Your Knowledge
Test your understanding of Regex Basics with these quick questions.