ใช้ \S+ (S พิมพ์ใหญ่ + quantifier +) เพื่อจับคู่ ลำดับอักขระที่ไม่ใช่ whitespace 1 ตัวขึ้นไป
ตัวอย่าง: search() - หาครั้งแรก
import re foo = re.search(r'\S+', 'Need for Speed 2') print(foo)
ผลลัพธ์
<_sre.SRE_Match object at 0x...>
จับคู่ "Need" (non-whitespace sequence แรก)
ตัวอย่าง: findall() - หาทั้งหมด (แยกคำ)
import re foo = re.findall(r'\S+', 'Need for Speed 2') print(foo)
ผลลัพธ์
['Need', 'for', 'Speed', '2']
คำอธิบาย
\S= non-whitespace character (เทียบเท่า[^\s]หรือ[^ \t\n\r\f\v])+= 1 ครั้งขึ้นไปfindall(r'\S+', ...)แยกคำ/token โดยใช้ whitespace เป็น delimiter → ใช้ได้แทนstr.split()ในบางกรณี
สรุป \s vs \S
| Pattern | ความหมาย | จับคู่ได้ |
|---|---|---|
\s | Whitespace 1 ตัว | space, tab, newline |
\s+ | Whitespace 1+ ตัว | " ", "\n\t" |
\S | Non-whitespace 1 ตัว | a, 1, @ |
\S+ | Non-whitespace 1+ ตัว | hello, 123, word |