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

การจับคู่ Start และ End ใน Python Regex (Anchors + Word Boundary)

จับคู่ส่วนของสตริงที่ เริ่มต้นด้วย 'T' และจบด้วย 'y' โดยใช้ Anchors และ Word Boundary

ตัวอย่าง

import re
result = re.findall(r'\bT\S+y\b', 'TestCountry Hello')
print(result)

ผลลัพธ์

['TestCountry']

คำอธิบาย Pattern \bT\S+y\b

  • \b - Word boundary (ขอบเขตคำ)
  • T - ตัวอักษร T ตรงตัว
  • \S+ - Non-whitespace 1+ ตัว (เนื้อหาคำ)
  • y - ตัวอักษร y ตรงตัว
  • \b - Word boundary (จบคำ)

การจับคู่ Start/End ของ String ทั้งหมด

>> import re
>>> s = 'TestCountry Hello'

# เริ่มต้น string
>>> re.findall(r'^\w+', s)
['TestCountry']

# จบ string
>>> re.findall(r'\w+$', s)
['Hello']

# ทั้งต้นและจบ (full string match)
>>> re.findall(r'^\w+\s+\w+$', s)
['TestCountry Hello']

Multiline Mode (re.M)

>> s = 'Line one\nLine two\nLine three'
>>> re.findall(r'^\w+', s, re.M)
['Line', 'Line', 'Line']
>>> re.findall(r'\w+$', s, re.M)
['one', 'two', 'three']