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

Cách tách chuỗi (split) bằng nhiều delimiter trong Python Regex

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ăngstr.split()re.split()
Multiple delimitersKhông (chỉ 1 string)Có (regex pattern)
Regex powerKhôngCó
Keep delimiterKhôngCó (nếu pattern có capturing group)
PerformanceNhanh hơnChậ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']