Capturing Groups का उपयोग
Parentheses string का वह हिस्सा save करते हैं जो वे match करते हैं।
In this page:
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
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
Login to try C/C++/Java/PHP code in the editor
आम गलतियां
- एक failed match के बाद $1 इस्तेमाल करना और पुरानी value की उम्मीद करना
- nested groups की numbering mix up करना
- $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: