Regular Expressions Trong Python: Xử Lý Chuỗi Và Trích Xuất Dữ Liệu Mạnh Mẽ
Chia sẻ
"Hướng dẫn dùng Regular Expressions (regex) trong Python: pattern matching, tìm kiếm, thay thế, trích xuất email/số điện thoại/URL từ text."
1. Regular Expressions (Regex) Là Gì?
Regex là pattern matching language dùng để tìm, validate, và trích xuất chuỗi theo mẫu. Trong Python, module re cung cấp đầy đủ công cụ regex. Regex được dùng khắp nơi: validate email, trích xuất số điện thoại từ text, parse log files, clean data.
Regex khó học nhưng cực kỳ powerful — 1 dòng regex có thể thay thế 20 dòng string manipulation code. Bài viết hướng dẫn từ cơ bản đến nâng cao với ví dụ thực tế.
2. Các Hàm re Cơ Bản
import re
text = "Liên hệ: 0912-345-678 hoặc email@example.com"
# re.search() — tìm match đầu tiên
match = re.search(r"\d{4}-\d{3}-\d{3}", text)
print(match.group()) # 0912-345-678
# re.findall() — tìm TẤT CẢ matches
emails = re.findall(r"[\w.-]+@[\w.-]+", text)
print(emails) # ["email@example.com"]
# re.sub() — thay thế
cleaned = re.sub(r"\d", "X", text) # Ẩn số
# re.split() — tách chuỗi theo pattern
parts = re.split(r"[,;\s]+", "a, b; c d") # ["a","b","c","d"]3. Metacharacters Và Quantifiers
\d = digit, \w = word char, \s = whitespace, . = any char, ^ = đầu chuỗi, $ = cuối chuỗi. Quantifiers: * = 0+, + = 1+, ? = 0 hoặc 1, {n} = chính xác n, {n,m} = từ n đến m lần. Luôn dùng raw string r"..." để tránh escape issues.
4. Groups Và Named Groups
# Groups — capture parts of match
date_pattern = r"(\d{2})/(\d{2})/(\d{4})"
match = re.search(date_pattern, "Ngày 15/03/2024")
day, month, year = match.groups() # ("15", "03", "2024")
# Named Groups — dễ đọc hơn
pattern = r"(?P\d{2})/(?P\d{2})/(?P\d{4})"
match = re.search(pattern, "15/03/2024")
print(match.group("year")) # 20245. Lookahead Và Lookbehind
Lookahead (?=...) và Lookbehind (?<=...) match vị trí mà KHÔNG consume characters. Positive lookahead: \d+(?=₫) match số trước ₫. Negative lookbehind: (?<!\$)\d+ match số KHÔNG có $ phía trước.
# Tìm số tiền trước ₫ (không capture ₫)
prices = re.findall(r"[\d,]+(?=\s*₫)", "Giá: 150,000 ₫ và 250,000 ₫")
# ["150,000", "250,000"]
# Tìm từ sau "Mr." hoặc "Ms."
names = re.findall(r"(?<=(?:Mr|Ms)\.)\s*\w+", "Mr.Nguyen và Ms.Tran")6. Ứng Dụng Thực Tế: Data Cleaning
import pandas as pd
# Extract phone numbers from messy text column
df["phone"] = df["contact"].str.extract(r"(0\d{9,10})")
# Validate email format
df["valid_email"] = df["email"].str.match(
r"^[\w.-]+@[\w.-]+\.[a-zA-Z]{2,}$"
)
# Clean Vietnamese text: remove diacritics
import unicodedata
def remove_accents(text):
nfkd = unicodedata.normalize("NFKD", text)
return "".join(c for c in nfkd if not unicodedata.combining(c))7. Regex Tips Và Common Patterns
1) Test trên regex101.com trước khi code. 2) Dùng re.VERBOSE flag để viết regex nhiều dòng có comment. 3) Compile pattern nếu dùng nhiều lần: pat = re.compile(r"..."). 4) Regex greedy (.*) mặc định — dùng .*? cho non-greedy.
8. Kết Luận
Regex là skill thiết yếu cho Data Analyst dùng Python. Thành thạo re.search, re.findall, re.sub + groups + lookahead là đủ xử lý 90% bài toán text processing. Luyện tập trên regex101.com rồi apply vào Pandas str methods.
Bình luận
Đăng nhập để tham gia bình luận
Đăng nhậpNhận bài viết mới nhất
Đăng ký để nhận thông báo khi có bài viết mới. Không spam, chỉ kiến thức chất lượng.
Bài viết liên quan
Khám phá thêm các bài viết cùng chủ đề


