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

Cách khớp chỉ space và newline bằng Python Regex

Dùng \s+ để khớp một hoặc nhiều whitespace (bao gồm space, tab, newline). Nếu chỉ muốn space và newline (loại tab), dùng [ \n]+.

Ví dụ: Tìm tất cả whitespace sequences

import re

foo = ' I find \n Tutorialspoint \n useful'
result = re.findall(r'\s+', foo)
print(result)
# [' ', ' ', '\n ', '\n ']

Kết quả

[' ', ' ', '\n ', '\n ']

Giải thích

  • \s khớp: space, \t, \n, \r, \f, \v.
  • + gom nhóm các whitespace liên tiếp thành 1 match.
  • Kết quả bao gồm cả space lẫn newline trong mỗi match.

Chỉ khớp space VÀ newline (loại tab)


# Chỉ space và newline
re.findall(r'[ \n]+', text)

# Tách riêng: chỉ space
re.findall(r' +', text)

# Chỉ newline
re.findall(r'\n+', text)

Ứng dụng: Đếm số dòng trống


text = "Line 1\n\n\nLine 2\n\nLine 3"
blank_lines = re.findall(r'\n{2,}', text)
print(len(blank_lines))  # 2 nhóm newline kép trở lên