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

Cách khớp tab và newline nhưng KHÔNG khớp space trong Python Regex

Dùng character class [\n\t] để khớp chính xác newline (\n) và tab (\t), loại trừ space thông thường.

Ví dụ

import re

text = """I find     Tutorialspoint useful"""

# Chỉ tìm \n và \t
matches = re.findall(r'[\n\t]', text)
print(matches)
# ['\n']

Kết quả

['\n']

Giải thích

  • [\n\t]: Character class chứa 2 ký tự: newline và tab.
  • Space thông thường (' ') không nằm trong class này → không khớp.
  • findall trả về list các ký tự khớp.

Các pattern liên quan

PatternKhớp
[\n\t]Chỉ newline và tab
[\n\t\r]Newline, tab, carriage return
\sTất cả whitespace (space, \t, \n, \r, \f, \v)
[^\S\n\t]Chỉ space (non-whitespace trừ \n,\t) - phức tạp
(?!\n|\t)Space không theo sau \n/\t - lookahead

Ứng dụng: Tách dòng nhưng giữ space trong dòng


# Split theo newline/tab, giữ space
parts = re.split(r'[\n\t]+', text)
print(parts)
# ['I find     Tutorialspoint useful']