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

Khớp whitespace trong regex Python (\s)

\s khớp một ký tự khoảng trắng: space, tab (\t), newline (\n), carriage return (\r), form feed (\f), vertical tab (\v).

Ví dụ: search

import re
result = re.search(r'\s', 'The Indian Express')
print(result.group())  # ' ' (space đầu tiên)

Ví dụ: findall (tất cả whitespace)

result = re.findall(r'\s', 'The Indian Express')
print(result)  # [' ', ' ']

Ví dụ: split bằng whitespace

re.split(r'\s+', 'The   Indian\tExpress\nLine')
# ['The', 'Indian', 'Express', 'Line']