Greedy बनाम non-greedy matching

Python में Regular Expressions

Maria Eugenia Inzaugarat

Data Scientist

Greedy बनाम non-greedy matching

  • Matching के दो प्रकार:

    • Greedy
    • Non-greedy या lazy
  • Standard quantifiers डिफॉल्ट रूप से greedy होते हैं: *, +, ?, {num, num}

Python में Regular Expressions

Greedy matching

  • Greedy: जितने संभव हों उतने characters match करे

  • Longest match लौटाता है

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

Python में Regular Expressions

Greedy matching

  • बहुत अधिक characters match होने पर backtrack करता है

  • एक-एक कर characters छोड़ता है

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

Python में Regular Expressions

Non-greedy matching

  • Lazy: जितने ज़रूरी हों उतने ही characters match करे
  • Shortest match लौटाता है
  • Greedy quantifiers के बाद ? जोड़ें
import re
re.match(r"\d+?", "12345bcada")
<re.Match object; span=(0, 1), match='1'>

Python में Regular Expressions

Non-greedy matching

  • बहुत कम characters match होने पर backtrack करता है

  • एक-एक कर characters बढ़ाता है

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

Python में Regular Expressions

अभ्यास करते हैं!

Python में Regular Expressions

Preparing Video For Download...