Character classes and quantifiers
Classes describe which characters may appear, and quantifiers say how many times.
In this page:
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
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
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Forgetting that . does not match a newline
- Using * when you need at least one match
- 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: