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

Global Matching करना

g modifier पहले पर रुकने की बजाय हर match ढूंढता है।

In this page:

  1. Global Matching

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

perl
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
{# 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. /g भूल जाना और सिर्फ पहला match पाना
  2. एक loop के बाहर scalar context में //g इस्तेमाल करना और हर call पर सिर्फ एक match पाना
  3. यह मान लेना कि 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:

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.