Perl Cheat Sheet Page 2

ADVERTISEMENT

Matching and Regular Expressions
Test for
=~
Test for match
if ($x =~ /abc/) {
Does $x have the string “abc”
...}
anywhere in it?
Match
!~
Test for non-match
if ($x !~ /abc/) {
Does $x NOT have the string
...}
“abc” anywhere in it?
$_
Default variable
if (/abcd/) {
// and s/// work on $_ by default,
s/bc/x/ }
no =~ needed
Substitute
s///
Do a Substitution
$x =~ s/abc/def/;
Replace (only) first occurrence
of “abc” in $x with def
Match/ Sub
i
Ignore case.
/abc/i
Matches abc, ABC, aBc, etc.
Options
g
Global substitution.
s/a/c/g
Replace ALL occurrences
Special
.
Any one character
/a.c/
“arc”, “a9c”, but not “ac”.
(except \n)
Match Items
[ ]
Any one of.
/[abc]/
Any one of “a”, “b”, or “c”. [a-
zA-Z] matches any letter
\d
Digit (Same as [0-9])
/\d\d:\d\d/
“10:30” (but not “9:30”)
\s
Space, tab, or newline
/^\s*$/
An empty line.
\
Literally match special
/1\+2/
“1+2”, not “1112”. The
characters: + * ( ) / [ ]
backslash “quotes” or “escapes”
\ | { } ^ $ @
the plus sign.
Item
^
Beginning of a line
/^a/
"arginine" but not "valine”.
Locations
$
End of a line
/a$/
"beta" but not "beat".
Item
?
An optional thing
/ab?c/
“ac” or “abc”.
Repetitions
*
Any number of copies
/a*/
"", "a", "aaa".
OR nothing at all
+
Any number of copies
/a+b/
"ab" or "aaab" but not "b".
{ }
m to n copies
/ab{2,4}c/
“abbc”, “abbbc”, “abbbbc”, but
not “abc” or “abbbbbc”
Misc
|
One or the other
/abc|def/
“abc” or “def”
Capture parts of match
/a(b(..)e)f/
“abcdef”. This will also set $1 to
in numbered variables
“bcde” and $2 to “cd”.
( )
AND group things
/a(bc)+d/
“abcd” or “abcbcbcbcd”
together for repetition,
etc.

ADVERTISEMENT

00 votes

Related Articles

Related forms

Related Categories

Parent category: Education
Go
Page of 2