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

การจับคู่ Whitespace ใน Python Regex (\s)

ใช้ \s (s พิมพ์เล็ก) เพื่อจับคู่ Whitespace character เพียงตัวเดียว (space, tab, newline, carriage return, form feed, vertical tab)

ตัวอย่าง: search() - หาครั้งแรก

import re
result = re.search(r'[\s]', 'The Indian Express')
print(result)

ผลลัพธ์

<_sre.SRE_Match object at 0x...>

จับคู่ space แรกระหว่าง "The" และ "Indian"

ตัวอย่าง: findall() - หาทั้งหมด

import re
result = re.findall(r'[\s]', 'The Indian Express')
print(result)

ผลลัพธ์

[' ', ' ']

พบ space 2 ตัว (ระหว่างคำ 3 คำ)

ข้อสังเกต: [\s] vs \s

[\s] และ \s ให้ผลลัพธ์เหมือนกัน (วงเล็บเหลี่ยมรอบ escape sequence ตัวเดียวไม่เปลี่ยนความหมาย) แต่นิยมเขียน \s ตรงๆ

Quantifiers กับ \s

>> re.findall(r'\s+', 'The  Indian\tExpress\nLine')
['  ', '\t', '\n']  # จับคู่ whitespace sequence แต่ละกลุ่ม