Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Giải thích Python Regular Expression Syntax đơn giản

Regular Expression (Regex) là chuỗi ký tự mô tả pattern để tìm kiếm, trích xuất, validate, thay thế text. Python module re cung cấp engine regex mạnh mẽ.

Hai loại ký tự trong Regex

LoạiVí dụÝ nghĩa
Literalsa, B, 1, _Khớp chính xác ký tự đó
Metacharacters. ^ $ * + ? { } [ ] \ | ( )Có ý nghĩa đặc biệt

Công cụ chính của Python Regex

  • Raw strings: r'pattern' - tránh escape confusion.
  • Quantifiers: * + ? {m,n} - số lượng lặp lại.
  • Character Classes: [abc], [a-z], [^abc], \d \w \s.
  • Groups: (...) capture, (?:...) non-capture, (?P...) named.
  • Alternation: a|b - hoặc.
  • Anchors: ^ $ \A \Z \b \B - vị trí.
  • Lookaround: (?=) (?!) (?<=) (? - assertion không tiêu thụ ký tự.

Ví dụ Pattern phổ biến

Workflow cơ bản


import re

# 1. Compile (tùy chọn, khuyến nghị cho pattern dùng lặp)
pattern = re.compile(r'\d+')

# 2. Search/Extract
match = pattern.search(text)      # Match đầu tiên
matches = pattern.findall(text)   # Tất cả matches
for m in pattern.finditer(text):  # Iterator với vị trí
    ...

# 3. Substitute
new_text = pattern.sub('REPLACEMENT', text)

Tài nguyên học thêm

  • Python docs: re module.
  • Regex101.com - Test/debug regex online.
  • Regular-Expressions.info - Reference chi tiết.
Mục đíchPattern
Email đơn giản[\w.+-]+@[\w-]+\.[\w.-]+
URLhttps?://[\w.-]+(?:\.[\w.-]+)+
IPv4(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}
Ngày YYYY-MM-DD\d{4}-\d{2}-\d{2}
Số điện thoại VN(?:\+84|0)[35789]\d{8}