#!/usr/bin/perl # Pattern Modifiers # # c Do not reset search position on a failed match when /g is in effect. # g Match globally, i.e., find all occurrences. # i Do case-insensitive pattern matching. # m Treat string as multiple lines. # o Compile pattern only once. # s Treat string as single line. # x Use extended regular expressions. # Metacharacters # # \ Quote the next metacharacter # ^ Match the beginning of the line # . Match any character (except newline) # $ Match the end of the line (or before newline at the end) # | Alternation # () Grouping # [] Character class # Greedy Quantifiers # # * Match 0 or more times # + Match 1 or more times # ? Match 1 or 0 times # {n} Match exactly n times # {n,} Match at least n times # {n,m} Match at least n but not more than m times # Non-Greedy Quantifiers # # *? Match 0 or more times # +? Match 1 or more times # ?? Match 1 or 0 times # {n}? Match exactly n times # {n,}? Match at least n times # {n,m}? Match at least n but not more than m times # Escaped Characters # \t tab (HT, TAB) # \n newline (LF, NL) # \r return (CR) # \f form feed (FF) # \a alarm (bell) (BEL) # \e escape (think troff) (ESC) # \033 octal char (think of a PDP-11) # \x1B hex char # \c[ control char # \l lowercase next char (think vi) # \u uppercase next char (think vi) # \L lowercase till \E (think vi) # \U uppercase till \E (think vi) # \E end case modification (think vi) # \Q quote (disable) pattern metacharacters till \E # ??? # # \w Match a "word" character (alphanumeric plus "_") # \W Match a non-word character # \s Match a whitespace character # \S Match a non-whitespace character # \d Match a digit character # \D Match a non-digit character # Zero-Width Assertions: # # \b Match a word boundary # \B Match a non-(word boundary) # \A Match only at beginning of string # \Z Match only at end of string, or before newline at the end # \z Match only at end of string # \G Match only where previous m//g left off (works only with /g) my $string = "My name is Doug and my ssn\tis 555-55-5555."; print "$string\n"; print "\nSSN\n\n"; (my $ssn = $string) =~ s/\D//g; print "$ssn\n"; ($ssn = $string) =~ s/[^-0-9]//g; print "$ssn\n"; print "\nName\n\n"; $string =~ /name is (\w+)/; print "$1\n"; $string =~ /ssn\s+is\s+([-0-9]+)/; print "$1\n"; my $template = <<"EOD"; Title Text Text EOD print "\nGreedy\n\n"; while($template =~ //g) { print "$1\n"; } print "\nNon-Greedy\n\n"; while($template =~ //g) { print "$1\n"; }