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

Character Classes और Quantifiers

Classes describe करती हैं कि कौन-से characters appear हो सकते हैं, और quantifiers बताते हैं कितनी बार।

Character Classes और Quantifiers

[aeiou] जैसी एक character class set से एक character match करती है, और shortcuts में शामिल हैं digits के लिए \d, word characters के लिए \w, और whitespace के लिए \s, capital versions opposite मतलब रखते हुए। dot एक newline को छोड़कर किसी भी character से match करता है। Quantifiers repetition control करते हैं: * मतलब zero या more, + मतलब one या more, ? मतलब zero या one, और {n,m} एक exact range देता है।

Note: ^, $, और \b जैसे anchors एक position से match करते हैं, एक character से नहीं।

उदाहरण: Character classes and quantifiers

perl
use strict;
use warnings;

my @tests = ("2024-05-17", "abc123", "hello world", '[email protected]', "");
for my $t (@tests) {
    my @found;
    push @found, "date"     if $t =~ /^\d{4}-\d{2}-\d{2}$/;
    push @found, "digits"   if $t =~ /\d+/;
    push @found, "space"    if $t =~ /\s/;
    push @found, "email"    if $t =~ /^\w+@\w+\.[a-z]+$/;
    push @found, "vowel"    if $t =~ /[aeiou]/;
    push @found, "empty"    if $t =~ /^$/;
    printf "%-18s %s\n", "'$t'", join(",", @found) || "-";
}
print "a.c matches abc\n" if "abc" =~ /a.c/;
print "a\\.c does not match abc\n" if "abc" !~ /a\.c/;

# Output:
# '2024-05-17'       date,digits
# 'abc123'           digits,vowel
# 'hello world'      space,vowel
# '[email protected]' email,vowel
# ''                 empty
# a.c matches abc
# a\.c does not match abc
{# 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. यह भूल जाना कि . एक newline से match नहीं करता
  2. जब आपको कम से कम एक match चाहिए * इस्तेमाल करना
  3. literally मतलब होने पर . और ? जैसे special characters escape करना भूल जाना
चैप्टर सारांश
  • [abc] एक listed character से match करता है
  • \d \w \s shortcut classes हैं
  • * + ? {n,m} quantifiers हैं
  • एक backslash से metacharacters escape करें
🔒

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.