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

Cách viết Regex khớp số thực (floating point) trong Python

Regex khớp số thực chuẩn cần xử lý: dấu ±, phần nguyên, phần thập phân, khoa học (e/E).

Pattern chuẩn (RFC/comprehensive)

import re

# [±]? ( \d+ (\.\d*)? | \.\d+ ) ([eE][±]?\d+)?
float_pattern = r'[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?'

tests = ['234.6789', '0.45', '-12.5', '+3.14', '.75', '42', '1e10', '-5.2E-3', '3.']

for t in tests:
    m = re.match(float_pattern, t)
    print(f'{t:>10} -> {m.group() if m else "NO MATCH"}')

Kết quả


  234.6789 -> 234.6789
      0.45 -> 0.45
    -12.5 -> -12.5
    +3.14 -> +3.14
      .75 -> .75
        42 -> 42
      1e10 -> 1e10
   -5.2E-3 -> -5.2E-3
        3. -> 3.

Phân tích Pattern

PhầnRegexÝ nghĩa
Sign[+-]?Dấu + hoặc - (tùy chọn)
Số chính(\d+(\.\d*)?|\.\d+)Hoặc: digits + optional(.digits) HOẎC: .digits
Exponent([eE][+-]?\d+)?Tùy chọn: e/E + sign + digits

Các biến thể thường dùng


# Chỉ số thực có dấu chấm (bắt buộc có .)
r'[+-]?\d*\.\d+'

# Số thực hoặc số nguyên
r'[+-]?(\d+\.\d*|\.\d+|\d+)'

# Chỉ số dương
r'\d+(\.\d*)?|\.\d+'

Ứng dụng: Extract tất cả số từ text


text = "Temp: -11.7°C, pressure 1013.25 hPa, altitude 1.2e3 m"
numbers = re.findall(r'[+-]?(?:\d+\.\d*|\.\d+|\d+)(?:[eE][+-]?\d+)?', text)
print(numbers)
# ['-11.7', '1013.25', '1.2e3']

Lưu ý

  • Pattern này khớp substring trong chuỗi lớn. Dùng ^...$ cho validate toàn chuỗi.
  • Không khớp 'NaN', 'Inf', hex, binary.
  • Để parse an toàn: float(match.group()) sau khi regex validate.