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

Capturing Groups का उपयोग

Parentheses string का वह हिस्सा save करते हैं जो वे match करते हैं।

In this page:

  1. Capturing Groups

Capturing Groups

एक pattern में parentheses का हर pair $1, $2 वगैरह में text capture करता है, opening parenthesis की position से numbered। List context में, एक successful match captures को एक list की तरह return करता है, जो इन्हें variables में unpack करना आसान बनाता है। (?<name>...) लिखे Named captures %+ hash में store होते हैं।

Note: Capture variables अपनी values सिर्फ अगले successful match तक रखते हैं, इसलिए अगर आपको बाद में चाहिए इन्हें copy करें।

उदाहरण: Capturing groups

perl
use strict;
use warnings;

my $date = "Released on 2019-12-25.";
if ($date =~ /(\d{4})-(\d{2})-(\d{2})/) {
    print "year=$1 month=$2 day=$3\n";
}
my ($user, $domain) = "alice\@example.com" =~ /^(\w+)@([\w.]+)$/;
print "user=$user domain=$domain\n";
if ("John Smith" =~ /(?<first>\w+)\s+(?<last>\w+)/) {
    print "last name: $+{last}, first name: $+{first}\n";
}
if ("abc" =~ /(a)(b)?(x)?/) {
    print "group 3 is ", defined $3 ? "defined" : "undef", "\n";
}

# Output:
# year=2019 month=12 day=25
# user=alice domain=example.com
# last name: Smith, first name: John
# group 3 is undef
{# 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. एक failed match के बाद $1 इस्तेमाल करना और पुरानी value की उम्मीद करना
  2. nested groups की numbering mix up करना
  3. $1 इस्तेमाल करने से पहले यह check करना भूल जाना कि match succeed हुआ
चैप्टर सारांश
  • Parentheses $1, $2 ... में capture करते हैं
  • List context captures return करता है
  • (?<name>...) %+ में store करता है
  • Captures सिर्फ एक successful match के बाद इस्तेमाल करें
🔒

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.