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

Character classes and quantifiers

Classes describe which characters may appear, and quantifiers say how many times.

Character classes and quantifiers

A character class such as [aeiou] matches one character from the set, and shortcuts include \d for digits, \w for word characters and \s for whitespace, with the capital versions meaning the opposite. The dot matches any character except a newline. Quantifiers control repetition: * means zero or more, + means one or more, ? means zero or one, and {n,m} gives an exact range.

Note: Anchors such as ^, $ and \b match a position, not a character.

Example: 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
  1. Forgetting that . does not match a newline
  2. Using * when you need at least one match
  3. Forgetting to escape special characters like . and ? when you mean them literally
Chapter Summary
  • [abc] matches one listed character
  • \d \w \s are shortcut classes
  • * + ? {n,m} are quantifiers
  • Escape metacharacters with a backslash
🔒

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.