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

Backslashes ทำงานอย่างไรใน Python Regular Expressions

ตามเอกสาร Python metacharacter สำคัญที่สุดใน regex คือ backslash \ เหมือนใน string literals backslash ตามด้วยตัวอักษรต่างๆ เพื่อ special sequences ใช้ escape metacharacters ทั้งหมด เพื่อจับคู่ pattern จริง เช่น จับคู่ [ หรือ \ ให้ขึ้น \[ หรือ \\

ตัวอย่าง

import re
result = re.search('\d', '\d')
print(result)
result = re.search(r'\\d', '\d')
print(result.group())

ผลลัพธ์


None
\d

บรรทัดแรก: '\d' ใน string ปกติถูกตีความเป็น escape sequence แต่ \d ไม่ใช่ escape sequence ที่รู้จัก จึงคงอยู่ แต่ regex engine เห็น \d เป็น digit class จับคู่กับสตริง '\d' (backslash ตามด้วย d) ไม่จับคู่ จึงได้ None

บรรทัดที่สอง: ใช้ raw string r'\\d' คือสตริง 2 ตัวอักษร backslash และ d regex engine เห็น \\d คือ escaped backslash ตามด้วย d จับคู่กับสตริง '\d' ได้