Python không có scanf() như C. Regex mạnh hơn và linh hoạt hơn. Bảng mapping scanf format tokens → regex patterns.
Bảng mapping scanf() → Regex
| scanf() Token | Regex Equivalent |
|---|---|
%c | . |
%5c | .{5} |
%d | [-+]?\d+ |
%e, %E, %f, %g | [-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)? |
%i | [-+]?(0[xX][\dA-Fa-f]+|0[0-7]*|\d+) |
%o | [-+]?[0-7]+ |
%s | \S+ |
%u | \d+ |
%x, %X | [-+]?(0[xX])?[\dA-Fa-f]+ |
Ví dụ: Parse log line
# scanf format: "%s - %d errors, %d warnings"
# Input: "/usr/sbin/sendmail - 0 errors, 4 warnings"
import re
text = "/usr/sbin/sendmail - 0 errors, 4 warnings"
# Regex equivalent:
pattern = r'(\S+) - (\d+) errors, (\d+) warnings'
match = re.match(pattern, text)
if match:
filename = match.group(1)
errors = int(match.group(2))
warnings = int(match.group(3))
print(f'File: {filename}, Errors: {errors}, Warnings: {warnings}')
Kết quả
File: /usr/sbin/sendmail, Errors: 0, Warnings: 4
Ưu điểm Regex so với scanf()
- Mạnh hơn: lookaround, backreference, conditional, Unicode.
- Linh hoạt: optional parts, alternation, quantifiers phức tạp.
- Trả về Match object có vị trí, groups, span.
- Có thể compile và reuse.
Nhược điểm
- Verbose hơn scanf format string.
- Học curve dốc hơn.
- Hiệu năng chậm hơn scanf C thuần túy (nhưng đủ nhanh cho Python).
Thư viện third-party: parse
# pip install parse
from parse import parse
result = parse("{filename} - {errors:d} errors, {warnings:d} warnings", text)
print(result.named) # {'filename': '...', 'errors': 0, 'warnings': 4}