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

Regular Expression (Biểu thức chính quy) trong Python là gì?

Regular Expression (Regex / Regexp) là dãy ký tự định nghĩa mẫu tìm kiếm (pattern) trong văn bản. Dùng để tìm, trích xuất, xác thực, thay thế, tách chuỗi.

Ứng dụng phổ biến

  • Validate: email, phone, URL, date, IP...
  • Extract: số điện thoại, giá tiền, hashtag, mention...
  • Clean: xóa thẻ HTML, chuẩn hóa whitespace...
  • Parse: log file, CSV, config...
  • Refactor: rename biến, tìm code pattern...

Module re trong Python

import re

# Tìm kiếm
re.search(pattern, string)
re.match(pattern, string)
re.findall(pattern, string)
re.finditer(pattern, string)  # iterator Match objects

# Thay thế
re.sub(pattern, repl, string)
re.subn(pattern, repl, string)  # trả về (new_string, count)

# Tách chuỗi
re.split(pattern, string)

# Compile (tái sử dụng pattern)
regex = re.compile(pattern)
regex.search(string)

Metacharacter cơ bản

Ký tựÝ nghĩa
.Bất kỳ ký tự nào (trừ \n)
\dChữ số [0-9]
\DKhông phải chữ số
\wWord char [a-zA-Z0-9_]
\WKhông phải word char
\sWhitespace
\SKhông phải whitespace
^Đầu chuỗi/dòng
$Cuối chuỗi/dòng
* + ? {m,n}Quantifier (lặp)
|Alternation (hoặc)
()Grouping + capturing
[]Character class