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

Cách khớp mọi ký tự trừ space và newline trong Python Regex

Dùng negated character class [^ \n] hoặc [^\s] (tương đương \S) để khớp mọi ký tự trừ whitespace (space, tab, newline...).

Ví dụ: Khớp chuỗi KHÔNG chứa space và newline

import re

pattern = r'^[^ \n]*$'  # Từ đầu đến cuối, chỉ chứa ký tự không phải space/newline

tests = [
    "IfindTutorialspointuseful",      # Không space, không newline
    "I find Tutorialspointuseful",    # Có space
    "Ifind Tutorialspointuseful",     # Có space
]

for test in tests:
    match = re.match(pattern, test)
    print(f"'{test[:30]}...' -> {match is not None}")

Kết quả

'IfindTutorialspointuseful' -> True
'I find Tutorialspointuseful' -> False
'Ifind Tutorialspointuseful' -> False

Các cách viết tương đương

PatternÝ nghĩa
[^ \n]Trừ space và newline cụ thể
[^\s]Trừ tất cả whitespace (space, tab, newline, \r, \f, \v)
\SViết tắt của [^\s] (non-whitespace)

Ví dụ thực tế: Extract token không chứa space

import re

text = "token1=value1 token2=value2"
# Khớp key=value (không chứa space)
pattern = r'(\S+)=(\S+)'
print(re.findall(pattern, text))
# [('token1', 'value1'), ('token2', 'value2')]

Lưu ý

  • ^ và $ anchor đầu/cuối chuỗi (hoặc dòng với re.M).
  • * = 0 hoặc nhiều lần. Dùng + nếu yêu cầu ít nhất 1 ký tự.
  • \S gọn hơn và nhanh hơn [^\s].