Greedy और Non-greedy Matching
Default से quantifiers जितना हो सके text grab करते हैं, और एक question mark इन्हें जितना हो सके कम लेने देता है।
In this page:
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
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
Login to try C/C++/Java/PHP code in the editor
आम गलतियां
- delimiters के बीच .* इस्तेमाल करना और बहुत ज़्यादा capture करना
- lazy matching के लिए ? भूल जाना
- यह मान लेना कि 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: