Regular Expression

Predefined character classes

Several character classes are abbreviated by special backslashed letters:

Special
character
Matches aSame as
\ddigit[0-9]
\Dnon-digit[^0-9]
\walphanumeric character[a-zA-Z0-9_]
\Wnon-alphanumeric character[^a-zA-Z0-9_]
\swhitespace character (space, tab, newline...)[\s\t\n\r\f]
\Snon-whitespace character[^\s\t\n\r\f]

Other special backslashed letters are:

Special
character
Meaning
\aalarm (beep)
\nnewline
\rcarriage return
\ttab
\fformfeed
\eescape

Example

The following program asks the user to enter a date and time in the following format: 08-OCT-2012 16:30, and then checks whether they were entered correctly.
#!/usr/bin/perl

print "Please enter date and time in the format \"DD-MMM-YYYY  HH:MM\"\n";
my $entry = <STDIN>;
chop ($entry);

if ($entry =~ /\d\d-\w\w\w-\d\d\d\d  \d\d:\d\d/) {
   print "Great!\n";
} else {
   print "Wrong format!\n";
}

# Note: an even better conditional would be:
# if ($entry =~ /[0-3]\d-\w\w\w-\d\d\d\d  [0-2]\d:[0-5]\d/) {   }

Table of Contents.
Previous | Next.