Introduction
Regular expressions (regex) are patterns used to match character combinations in strings. They are a powerful tool for text processing, validation, and data extraction.
Basic Syntax
# Literal matching
/Hello/ matches "Hello"
# Special characters
. Any single character
d Any digit (0-9)
w Word character (a-z, A-Z, 0-9, _)
s Whitespace (space, tab, newline)
# Examples
/HellosWorld/ matches "Hello World"
/d{3}/ matches "123"
/w+@w+.w+/ matches "user@example.com"
Practical Examples
# Match email addresses
/[w.]+@+.+/
# Match phone numbers
/d{3}-d{3}-d{4}/
# Match URLs
/https?://[w.-]+/
# In JavaScript
const regex = /d+/g;
const result = "I have 5 cats and 3 dogs".match(regex);
// ["5", "3"]
Using Regex in Code
# Python
import re
pattern = r'd+'
result = re.findall(pattern, "12 apples and 34 oranges")
# ['12', '34']
# JavaScript
const pattern = /d+/g;
const result = "12 apples".match(pattern);
Summary
Regex uses patterns to find and manipulate text. Start with basic metacharacters like ., d, w, and s, then build complex patterns for real-world tasks.
YouTip