🔍 Biểu Thức Chính Quy (Regular Expressions) - Siêu Công Cụ Tìm Kiếm
Mục tiêu: Học cách sử dụng Regex để tìm kiếm, kiểm tra và xử lý văn bản như một chuyên gia! 🎯
🤔 Regular Expression (Regex) Là Gì? (Giải Thích Siêu Dễ)
Regular Expression giống như công thức siêu mạnh để tìm kiếm trong văn bản:
🔎 Hãy Tưởng Tượng...
- Regex = Kính lúp thông minh 🔍
- Có thể tìm mọi thứ theo pattern cụ thể
- Nhanh và chính xác hơn tìm kiếm thường
- Linh hoạt - tìm được cả những gì "giống giống"
🎯 Regex Có Thể Làm Gì?
- ✅ Kiểm tra email hợp lệ:
[email protected]
- ✅ Tìm số điện thoại:
0901234567
hoặc(028) 1234-5678
- ✅ Trích xuất URL:
https://behitek.com
- ✅ Validate mật khẩu: Có chữ hoa, số, ký tự đặc biệt
- ✅ Thay thế văn bản thông minh: Đổi format ngày tháng
📚 Nhập Môn Regex với Python
import re
# Module 're' của Python để làm việc với regex
print("🎯 REGEX CƠ BẢN VỚI PYTHON")
print("=" * 50)
# Ví dụ đầu tiên: Tìm từ "Python" trong text
text = "Tôi yêu Python! Python rất tuyệt vời. Python là tương lai!"
# Tìm tất cả từ "Python"
result = re.findall(r'Python', text)
print(f"📝 Text: {text}")
print(f"🔍 Tìm 'Python': {result}")
print(f"📊 Tìm được {len(result)} lần")
print("\n" + "-" * 50)
# Tìm với case-insensitive (không phân biệt hoa thường)
result_2 = re.findall(r'python', text, re.IGNORECASE)
print(f"🔍 Tìm 'python' (không phân biệt hoa/thường): {result_2}")
🔤 Các Ký Tự Đặc Biệt Trong Regex
📋 Bảng Ký Tự Cơ Bản
Ký tự | Ý nghĩa | Ví dụ | Giải thích |
---|---|---|---|
. | Bất kỳ ký tự nào | a.c | abc , aXc , a9c |
* | 0 hoặc nhiều lần | ab*c | ac , abc , abbbbc |
+ | 1 hoặc nhiều lần | ab+c | abc , abbc , abbbbc |
? | 0 hoặc 1 lần | ab?c | ac , abc |
^ | Bắt đầu chuỗi | ^Hello | Chuỗi bắt đầu bằng "Hello" |
$ | Kết thúc chuỗi | end$ | Chuỗi kết thúc bằng "end" |
\d | Chữ số (0-9) | \d+ | 123 , 456 , 7 |
\w | Chữ cái, số, _ | \w+ | hello , test_123 |
\s | Khoảng trắng | \s+ | Dấu cách, tab, xuống dòng |
🎮 Thực Hành Các Ký Tự Đặc Biệt
import re
def demo_regex_patterns():
"""Demo các pattern regex cơ bản"""
test_text = """
Chào mừng đến với Behitek Academy!
Email: [email protected]
Phone: 0901234567
Website: https://behitek.com
Ngày: 29/09/2024
Giờ: 14:30
Giá: $199.99
"""
print("📝 TEXT MẪU:")
print(test_text)
print("\n🔍 DEMO REGEX PATTERNS:")
print("=" * 60)
# 1. Tìm tất cả số
numbers = re.findall(r'\d+', test_text)
print(f"🔢 Tìm tất cả số: {numbers}")
# 2. Tìm từ (chỉ chữ cái)
words = re.findall(r'[a-zA-ZÀ-ỹ]+', test_text)
print(f"🔤 Tìm từ: {words[:5]}...") # Chỉ hiển thị 5 từ đầu
# 3. Tìm email
emails = re.findall(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b', test_text)
print(f"📧 Tìm email: {emails}")
# 4. Tìm URL
urls = re.findall(r'https?://[^\s]+', test_text)
print(f"🌐 Tìm URL: {urls}")
# 5. Tìm số điện thoại (pattern Việt Nam)
phones = re.findall(r'0\d{9}', test_text)
print(f"📞 Tìm SĐT: {phones}")
# 6. Tìm ngày tháng (dd/mm/yyyy)
dates = re.findall(r'\d{2}/\d{2}/\d{4}', test_text)
print(f"📅 Tìm ngày: {dates}")
# 7. Tìm giá tiền
prices = re.findall(r'\$\d+\.\d{2}', test_text)
print(f"💰 Tìm giá: {prices}")
# Chạy demo
demo_regex_patterns()
🎯 Các Phương Thức Regex Quan Trọng
import re
def demo_regex_methods():
"""Demo các phương thức regex quan trọng"""
text = "Python là ngôn ngữ lập trình tuyệt vời. Python được yêu thích bởi nhiều lập trình viên."
print("🛠️ CÁC PHƯƠNG THỨC REGEX:")
print("=" * 50)
# 1. re.search() - Tìm match đầu tiên
match = re.search(r'Python', text)
if match:
print(f"🔍 re.search(): Tìm thấy '{match.group()}' ở vị trí {match.start()}-{match.end()}")
# 2. re.match() - Kiểm tra từ đầu chuỗi
match_start = re.match(r'Python', text)
if match_start:
print(f"✅ re.match(): Chuỗi bắt đầu bằng 'Python'")
else:
print(f"❌ re.match(): Chuỗi KHÔNG bắt đầu bằng 'Python'")
# 3. re.findall() - Tìm tất cả
all_matches = re.findall(r'Python', text)
print(f"📋 re.findall(): Tìm thấy {len(all_matches)} lần: {all_matches}")
# 4. re.finditer() - Tìm tất cả với thông tin vị trí
matches_with_pos = list(re.finditer(r'Python', text))
print(f"📍 re.finditer(): Chi tiết vị trí:")
for i, match in enumerate(matches_with_pos):
print(f" Match {i+1}: '{match.group()}' ở vị trí {match.start()}-{match.end()}")
# 5. re.sub() - Thay thế
new_text = re.sub(r'Python', 'Java', text)
print(f"🔄 re.sub(): Thay 'Python' → 'Java'")
print(f" Kết quả: {new_text}")
# 6. re.split() - Tách chuỗi
sentences = re.split(r'[.!?]', text)
sentences = [s.strip() for s in sentences if s.strip()] # Loại bỏ chuỗi rỗng
print(f"✂️ re.split(): Tách câu:")
for i, sentence in enumerate(sentences):
print(f" Câu {i+1}: {sentence}")
# Chạy demo
demo_regex_methods()
📧 Ví Dụ Thực Tế: Validation Email và Số Điện Thoại
import re
class DataValidator:
"""Class validation dữ liệu với regex"""
def __init__(self):
# Compile regex patterns để tăng hiệu suất
self.email_pattern = re.compile(
r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
)
# Pattern số điện thoại Việt Nam
self.phone_pattern = re.compile(
r'^(0[1-9])[0-9]{8}$|^\+84[1-9][0-9]{8}$'
)
# Pattern mật khẩu mạnh (ít nhất 8 ký tự, có chữ hoa, thường, số, ký tự đặc biệt)
self.password_pattern = re.compile(
r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$'
)
# Pattern URL
self.url_pattern = re.compile(
r'^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$'
)
def validate_email(self, email):
"""Kiểm tra email hợp lệ"""
if self.email_pattern.match(email):
print(f"✅ Email '{email}' hợp lệ")
return True
else:
print(f"❌ Email '{email}' không hợp lệ")
return False
def validate_phone(self, phone):
"""Kiểm tra số điện thoại Việt Nam hợp lệ"""
# Loại bỏ khoảng trắng và dấu gạch ngang
clean_phone = re.sub(r'[\s-]', '', phone)
if self.phone_pattern.match(clean_phone):
print(f"✅ SĐT '{phone}' hợp lệ")
return True
else:
print(f"❌ SĐT '{phone}' không hợp lệ")
return False
def validate_password(self, password):
"""Kiểm tra mật khẩu mạnh"""
if self.password_pattern.match(password):
print(f"✅ Mật khẩu mạnh")
return True
else:
print(f"❌ Mật khẩu yếu (cần ít nhất 8 ký tự, có chữ hoa, thường, số, ký tự đặc biệt)")
return False
def validate_url(self, url):
"""Kiểm tra URL hợp lệ"""
if self.url_pattern.match(url):
print(f"✅ URL '{url}' hợp lệ")
return True
else:
print(f"❌ URL '{url}' không hợp lệ")
return False
def extract_info_from_text(self, text):
"""Trích xuất thông tin từ văn bản"""
print(f"📝 Phân tích văn bản: {text}")
print("-" * 50)
# Tìm email
emails = self.email_pattern.findall(text)
if emails:
print(f"📧 Email tìm thấy: {emails}")
# Tìm số điện thoại
phones = re.findall(r'0[1-9]\d{8}', text)
if phones:
print(f"📞 SĐT tìm thấy: {phones}")
# Tìm URL
urls = re.findall(r'https?://[^\s]+', text)
if urls:
print(f"🌐 URL tìm thấy: {urls}")
# Tìm ngày tháng (nhiều định dạng)
date_patterns = [
r'\d{1,2}/\d{1,2}/\d{4}', # dd/mm/yyyy
r'\d{1,2}-\d{1,2}-\d{4}', # dd-mm-yyyy
r'\d{4}-\d{1,2}-\d{1,2}' # yyyy-mm-dd
]
dates = []
for pattern in date_patterns:
dates.extend(re.findall(pattern, text))
if dates:
print(f"📅 Ngày tháng tìm thấy: {dates}")
return {
'emails': emails,
'phones': phones,
'urls': urls,
'dates': dates
}
# Demo validation
def demo_validation():
"""Demo validation với regex"""
validator = DataValidator()
print("🔍 === DEMO VALIDATION VỚI REGEX ===")
print()
# Test email
print("📧 KIỂM TRA EMAIL:")
test_emails = [
"[email protected]",
"[email protected]",
"invalid-email",
"test@domain",
"[email protected]"
]
for email in test_emails:
validator.validate_email(email)
print()
# Test số điện thoại
print("📞 KIỂM TRA SỐ ĐIỆN THOẠI:")
test_phones = [
"0901234567",
"+84901234567",
"0123456789", # Đầu số cũ, không hợp lệ
"84901234567",
"090-123-4567"
]
for phone in test_phones:
validator.validate_phone(phone)
print()
# Test mật khẩu
print("🔐 KIỂM TRA MẬT KHẨU:")
test_passwords = [
"Password123!",
"password123",
"PASSWORD123!",
"Pass123!",
"VeryStrongPassword123@"
]
for password in test_passwords:
validator.validate_password(password)
print()
# Test URL
print("🌐 KIỂM TRA URL:")
test_urls = [
"https://behitek.com",
"http://www.example.com",
"https://subdomain.behitek.com/path",
"not-a-url",
"ftp://files.example.com"
]
for url in test_urls:
validator.validate_url(url)
print()
# Test trích xuất thông tin
print("🔍 TRÍCH XUẤT THÔNG TIN TỪ VĂN BẢN:")
sample_text = """
Liên hệ với chúng tôi:
Email: [email protected] hoặc [email protected]
Điện thoại: 0901234567, 0987654321
Website: https://behitek.com
Ngày cập nhật: 29/09/2024
Hạn chót: 2024-12-31
"""
validator.extract_info_from_text(sample_text)
# Chạy demo
demo_validation()