Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การจับคู่ Non-whitespace Character ใน Python Regex (\S+)

ใช้ \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ความหมายจับคู่ได้
\sWhitespace 1 ตัวspace, tab, newline
\s+Whitespace 1+ ตัว" ", "\n\t"
\SNon-whitespace 1 ตัวa, 1, @
\S+Non-whitespace 1+ ตัวhello, 123, word