Greedy vs. non-greedy matching

Regular Expressions ใน Python

Maria Eugenia Inzaugarat

Data Scientist

Greedy vs. non-greedy matching

  • วิธีการจับคู่ 2 แบบ:

    • Greedy
    • Non-greedy หรือ lazy
  • Quantifier มาตรฐานเป็น greedy โดยค่าเริ่มต้น: *, +, ?, {num, num}

Regular Expressions ใน Python

Greedy matching

  • Greedy: จับคู่อักขระให้ได้มากที่สุด

  • คืนค่า ผลลัพธ์ที่ยาวที่สุด

import re
re.match(r"\d+", "12345bcada")
<re.Match object; span=(0, 5), match='12345'>

Regular Expressions ใน Python

Greedy matching

  • ย้อนกลับเมื่อจับคู่อักขระมากเกินไป

  • คืนอักขระทีละตัว

import re
re.match(r".*hello", "xhelloxxxxxx")
<re.Match object; span=(0, 6), match='xhello'>

Regular Expressions ใน Python

Non-greedy matching

  • Lazy: จับคู่อักขระให้น้อยที่สุดเท่าที่จำเป็น
  • คืนค่า ผลลัพธ์ที่สั้นที่สุด
  • เพิ่ม ? ต่อท้าย greedy quantifier
import re
re.match(r"\d+?", "12345bcada")
<re.Match object; span=(0, 1), match='1'>

Regular Expressions ใน Python

Non-greedy matching

  • ย้อนกลับเมื่อจับคู่อักขระน้อยเกินไป

  • ขยายอักขระทีละตัว

import re
re.match(r".*?hello", "xhelloxxxxxx")
<re.Match object; span=(0, 6), match='xhello'>

Regular Expressions ใน Python

มาฝึกกันเถอะ!

Regular Expressions ใน Python

Preparing Video For Download...