← Back to Perl Course | Chapter 4: Regular Expressions | Lesson 7 of 7

Greedy और Non-greedy Matching

Default से quantifiers जितना हो सके text grab करते हैं, और एक question mark इन्हें जितना हो सके कम लेने देता है।

Greedy और Non-Greedy Matching

* और + जैसे Quantifiers greedy हैं, इसलिए वे सबसे लंबी possible string match करते हैं जो पूरे pattern को फिर भी succeed होने देती है। एक quantifier के बाद एक ? add करना इसे non-greedy (lazy) बनाता है, इसलिए यह जल्द से जल्द possible point पर रुकता है। यह difference तब matter करता है जब आप दो delimiters के बीच text extract करते हैं जो कई बार appear होते हैं।

Note: quotes के बीच text के लिए एक negated class जैसे [^"]* अक्सर एक lazy .*? से clearer और faster होता है।

उदाहरण: Greedy and non-greedy matching

perl
use strict;
use warnings;

my $html = "<b>bold</b> and <i>italic</i>";
my ($greedy) = $html =~ /<(.+)>/;
my ($lazy)   = $html =~ /<(.+?)>/;
print "greedy: $greedy\n";
print "lazy:   $lazy\n";
my @tags = $html =~ /<(\w+)>/g;
print "tags: @tags\n";
my $quoted = 'say "hi" and "bye"';
my @strings = $quoted =~ /"([^"]*)"/g;
print "quoted: @strings\n";
my ($first_word) = "aaa bbb" =~ /(a+?)/;
print "lazy a+?: $first_word\n";

# Output:
# greedy: b>bold</b> and <i>italic</i
# lazy:   b
# tags: b i
# quoted: hi bye
# lazy a+?: a
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. delimiters के बीच .* इस्तेमाल करना और बहुत ज़्यादा capture करना
  2. lazy matching के लिए ? भूल जाना
  3. यह मान लेना कि lazy quantifiers यह बदलते हैं कि कौन-से matches exist करते हैं बजाय इसके कि पहले कौन-सा chosen हो
चैप्टर सारांश
  • Greedy quantifiers जितना हो सके match करते हैं
  • ? add करना एक quantifier को lazy बनाता है
  • Lazy matching पहले delimiter पर रुकती है
  • [^x]* एक precise alternative है
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.