Global Matching करना
g modifier पहले पर रुकने की बजाय हर match ढूंढता है।
In this page:
Global Matching
List context में, //g सारे matches return करता है, या जब pattern में groups हों सारे matches के सारे captures। Scalar context में, उदाहरण के लिए एक while loop में, हर match पिछले वाले जहाँ रुका वहाँ से continue करता है, और pos() वह position report करता है। एक string में सारे matches के आर-पार चलने का यह standard तरीका है।
Note:
= () = /g से एक scalar को assign करना इन्हें रखे बिना matches count करता है।
उदाहरण: Global matching
use strict;
use warnings;
my $text = "cat bat rat mat";
my @all = $text =~ /(\w)at/g;
print "first letters: @all\n";
my $count = () = $text =~ /at/g;
print "count: $count\n";
while ($text =~ /(\w+)at/g) {
printf "found '%s' ending at position %d\n", $1, pos($text);
}
my %pairs = "a=1,b=2,c=3" =~ /(\w)=(\d)/g;
print join(", ", map { "$_ -> $pairs{$_}" } sort keys %pairs), "\n";
# Output:
# first letters: c b r m
# count: 4
# found 'c' ending at position 3
# found 'b' ending at position 7
# found 'r' ending at position 11
# found 'm' ending at position 15
# a -> 1, b -> 2, c -> 3
Login to try C/C++/Java/PHP code in the editor
आम गलतियां
- /g भूल जाना और सिर्फ पहला match पाना
- एक loop के बाहर scalar context में //g इस्तेमाल करना और हर call पर सिर्फ एक match पाना
- यह मान लेना कि loop खत्म होने के बाद automatically फिर से शुरू होता है
चैप्टर सारांश
- List-context //g सारे matches return करता है
- एक while loop में Scalar //g matches पर iterate करता है
- pos() current position देता है
- //g के साथ Captures एक flat list return करते हैं
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: