Dùng re.split() với pattern alternation | để tách chuỗi theo nhiều delimiter khác nhau.
Ví dụ
import re
text = 'Beautiful; Soup\n is, good: Python* application'
# Delimiters: ; , * \n :
# Pattern: ; | , | \* | \n | : (escape * vì là metacharacter)
pattern = r'; |, |\*|\n|:'
parts = re.split(pattern, text)
print(parts)
# ['Beautiful', 'Soup', ' is', 'good', ' Python', ' application']
Kết quả
['Beautiful', 'Soup', ' is', 'good', ' Python', ' application']
Cải tiến: Loại bỏ empty strings, strip whitespace
# Filter empty và strip
parts = [p.strip() for p in re.split(pattern, text) if p.strip()]
print(parts)
# ['Beautiful', 'Soup', 'is', 'good', 'Python', 'application']
Character Class thay cho Alternation (nhanh hơn)
Nếu delimiters là single characters, dùng character class:
# Tương đương: ; , * \n :
pattern = r'[;,\*\n:]'
parts = re.split(pattern, text)
print([p.strip() for p in parts if p.strip()])
# ['Beautiful', 'Soup', 'is', 'good', 'Python', 'application']
re.split() vs str.split()
| Tính năng | str.split() | re.split() |
|---|---|---|
| Multiple delimiters | Không (chỉ 1 string) | Có (regex pattern) |
| Regex power | Không | Có |
| Keep delimiter | Không | Có (nếu pattern có capturing group) |
| Performance | Nhanh hơn | Chậm hơn |
Keep delimiter (capturing group)
# Giữ delimiter trong kết quả
parts = re.split(r'([;,\*\n:])', text)
print(parts)
# ['Beautiful', ';', ' Soup', '\n', ' is', ',', ' good', ':', ' Python', '*', ' application']