Regular Expressions (Regex) are powerful tools for pattern matching and text processing. This resource covers everything from the basics of Regex to advanced concepts and practical applications in JavaScript.
---
### **1. Introduction to Regex**
#### **What is Regex?**
A regular expression is a sequence of characters that forms a search pattern. It is used for tasks like validation, searching, and replacing text.
- **Basic Syntax:**
- `/pattern/flags` is the general syntax.
- Patterns define what to search for.
- Flags modify how searches are conducted (e.g., global, case-insensitive).
#### **Using Regex in JavaScript**
Regex can be used through the `RegExp` object or with string methods like `.match()`, `.replace()`, and `.test()`.
```javascript
const regex = /hello/i; // Case-insensitive match
console.log(regex.test("Hello World")); // true
const str = "Hello, hello, HELLO!";
console.log(str.match(/hello/gi)); // ["Hello", "hello", "HELLO"]
```
---
### **2. Core Regex Concepts**
#### **Character Classes and Quantifiers**
- **Character Classes:**
- `[abc]`: Matches any character inside the brackets.
- `\d`: Matches any digit (0-9).
- `\w`: Matches any word character (alphanumeric + underscore).
- `\s`: Matches whitespace.
- **Quantifiers:**
- `*`: Zero or more occurrences.
- `+`: One or more occurrences.
- `?`: Zero or one occurrence.
- `{n,m}`: Between `n` and `m` occurrences.
```javascript
const pattern = /\d+/g;
console.log("Order1234".match(pattern)); // ["1234"]
```
#### **Anchors and Boundaries**
- `^`: Matches the beginning of a string.
- `$`: Matches the end of a string.
- `\b`: Matches a word boundary.
```javascript
const pattern = /^hello$/i;
console.log(pattern.test("Hello")); // true
```
#### **Capturing Groups and Backreferences**
- Use parentheses `()` to create capturing groups.
- Backreferences allow reuse of matched groups.
```javascript
const pattern = /(\w+)\s\1/;
console.log(pattern.test("hello hello")); // true
```
#### **Flags**
- `g`: Global search.
- `i`: Case-insensitive search.
- `m`: Multi-line search.
---
### **3. Advanced Regex Concepts**
#### **Lookaheads and Lookbehinds**
- **Positive Lookahead:** Matches if a pattern is followed by another.
- `\d(?=\$)`: Matches digits followed by a dollar sign.
- **Negative Lookahead:** Matches if a pattern is not followed by another.
- `\d(?!\$)`: Matches digits not followed by a dollar sign.
```javascript
const pattern = /\d(?=\$)/g;
console.log("10$, 20, 30$".match(pattern)); // ["1", "3"]
```
- **Lookbehind:** Matches a pattern preceded by another (supported in modern browsers).
- `(?<=\$)\d`: Matches digits preceded by a dollar sign.
#### **Optimizing and Debugging Regex**
- Use online tools like regex101.com to test patterns.
- Break complex expressions into smaller, testable components.
---
### **4. Practical Applications of Regex**
#### **Validate Form Inputs**
- Email Validation:
```javascript
const emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
console.log(emailPattern.test("user@example.com")); // true
```
- Password Validation:
```javascript
const passwordPattern = /^(?=.*[A-Z])(?=.*[a-z])(?=.*\d).{8,}$/;
console.log(passwordPattern.test("Password1")); // true
```
#### **Search and Replace Text**
```javascript
const str = "The quick brown fox jumps over the lazy dog.";
const updatedStr = str.replace(/fox/, "cat");
console.log(updatedStr); // "The quick brown cat jumps over the lazy dog."
```
#### **Extract Data from Strings**
```javascript
const log = "ERROR: Line 42";
const pattern = /ERROR: Line (\d+)/;
const match = log.match(pattern);
console.log(match[1]); // "42"
```
---
### **5. Practical Projects with Regex**
#### **1. Form Validation Suite**
Build a complete form validation suite for common inputs like emails, phone numbers, and passwords.
#### **2. Text Search and Replace Tool**
Create a tool that allows users to search for specific words or patterns in a text and replace them.
#### **3. Data Scraper**
Write a script to extract structured data from unstructured text, such as extracting phone numbers from a document.
---
This resource is designed to help developers master Regular Expressions in JavaScript, equipping them with the skills to tackle real-world problems with precision and efficiency.
0 Comments