PERLREQUICK(1) Perl Programmers Reference Guide PERLREQUICK(1)
NAME
perlrequick - Perl regular expressions quick start
DESCRIPTION
This page covers the very basics of understanding, creating and using regular expressions ('regexes') in Perl.
The Guide
Simple word matching
The simplest regex is simply a word, or more generally, a string of characters. A regex consisting of a word matches any string that
contains that word:
"Hello World" =~ /World/; # matches
In this statement, "World" is a regex and the "//" enclosing "/World/" tells perl to search a string for a match. The operator "=~"
associates the string with the regex match and produces a true value if the regex matched, or false if the regex did not match. In our
case, "World" matches the second word in "Hello World", so the expression is true. This idea has several variations.
Expressions like this are useful in conditionals:
print "It matches
" if "Hello World" =~ /World/;
The sense of the match can be reversed by using "!~" operator:
print "It doesn't match
" if "Hello World" !~ /World/;
The literal string in the regex can be replaced by a variable:
$greeting = "World";
print "It matches
" if "Hello World" =~ /$greeting/;
If you're matching against $_, the "$_ =~" part can be omitted:
$_ = "Hello World";
print "It matches
" if /World/;
Finally, the "//" default delimiters for a match can be changed to arbitrary delimiters by putting an 'm' out front:
"Hello World" =~ m!World!; # matches, delimited by '!'
"Hello World" =~ m{World}; # matches, note the matching '{}'
"/usr/bin/perl" =~ m"/perl"; # matches after '/usr/bin',
# '/' becomes an ordinary char
Regexes must match a part of the string exactly in order for the statement to be true:
"Hello World" =~ /world/; # doesn't match, case sensitive
"Hello World" =~ /o W/; # matches, ' ' is an ordinary char
"Hello World" =~ /World /; # doesn't match, no ' ' at end
perl will always match at the earliest possible point in the string:
"Hello World" =~ /o/; # matches 'o' in 'Hello'
"That hat is red" =~ /hat/; # matches 'hat' in 'That'
Not all characters can be used 'as is' in a match. Some characters, called metacharacters, are reserved for use in regex notation. The
metacharacters are
{}[]()^$.|*+?
A metacharacter can be matched by putting a backslash before it:
"2+2=4" =~ /2+2/; # doesn't match, + is a metacharacter
"2+2=4" =~ /2+2/; # matches, + is treated like an ordinary +
'C:WIN32' =~ /C:\WIN/; # matches
"/usr/bin/perl" =~ //usr/bin/perl/; # matches
In the last regex, the forward slash '/' is also backslashed, because it is used to delimit the regex.
Non-printable ASCII characters are represented by escape sequences. Common examples are " " for a tab, "
" for a newline, and "
" for a
carriage return. Arbitrary bytes are represented by octal escape sequences, e.g., "