Seth Woolley's Man Viewer

perlrequick(1) - perlrequick - Perl regular expressions quick start - man 1 perlrequick

([section] manual, -k keyword, -K [section] search, -f whatis)
man plain no title

PERLREQUICK(1)         Perl Programmers Reference Guide         PERLREQUICK(1)

       perlrequick - Perl regular expressions quick start

       This page covers the very basics of understanding, creating and using
       regular expressions ('regexes') in(1,8) Perl.

The Guide
       Simple word matching

       The simplest regex(3,7) is simply a word, or more generally, a string(3,n) of
       characters.  A regex(3,7) consisting of a word matches any string(3,n) that con-
       tains that word:

           "Hello World" =~ /World/;  # matches

       In this statement, "World" is a regex(3,7) and the "//" enclosing "/World/"
       tells perl to search a string(3,n) for a match.  The operator "=~" asso-
       ciates the string(3,n) with the regex(3,7) match and produces a true value if(3,n) the
       regex(3,7) matched, or false if(3,n) the regex(3,7) did not match.  In our case,
       "World" matches the second word in(1,8) "Hello World", so the expression is
       true.  This idea has several variations.

       Expressions like this are useful in(1,8) conditionals:

           print "It matches\n" if(3,n) "Hello World" =~ /World/;

       The sense of the match can be reversed by using "!~" operator:

           print "It doesn't match\n" if(3,n) "Hello World" !~ /World/;

       The literal string(3,n) in(1,8) the regex(3,7) can be replaced by a variable:

           $greeting = "World";
           print "It matches\n" if(3,n) "Hello World" =~ /$greeting/;

       If you're matching against $_, the "$_ =~" part can be omitted:

           $_ = "Hello World";
           print "It matches\n" if(3,n) /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(3,n) exactly in(1,8) order for the state-
       ment 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(1,8) the string:

           "Hello World" =~ /o/;       # matches 'o' in(1,8) 'Hello'
           "That hat is red" =~ /hat/; # matches 'hat' in(1,8) 'That'

       Not all characters can be used 'as is' in(1,8) a match.  Some characters,
       called metacharacters, are reserved for use in(1,8) regex(3,7) 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(3,7), 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 "\t" for a tab, "\n" for a newline, and "\r" for a
       carriage return.  Arbitrary bytes are represented by octal escape
       sequences, e.g., "\033", or hexadecimal escape sequences, e.g., "\x1B":

           "1000\t2000" =~ m(0\t2)        # matches
           "cat"        =~ /\143\x61\x74/ # matches, but a weird way to spell cat

       Regexes are treated mostly as double quoted strings, so variable sub-
       stitution works:

           $foo = 'house';
           'cathouse' =~ /cat$foo/;   # matches
           'housecat' =~ /${foo}cat/; # matches

       With all of the regexes above, if(3,n) the regex(3,7) matched anywhere in(1,8) the
       string(3,n), it was considered a match.  To specify where it should match,
       we would use the anchor metacharacters "^" and "$".  The anchor "^"
       means match at the beginning of the string(3,n) and the anchor "$" means
       match at the end of the string(3,n), or before a newline at the end of the
       string.  Some examples:

           "housekeeper" =~ /keeper/;         # matches
           "housekeeper" =~ /^keeper/;        # doesn't match
           "housekeeper" =~ /keeper$/;        # matches
           "housekeeper\n" =~ /keeper$/;      # matches
           "housekeeper" =~ /^housekeeper$/;  # matches

       Using character classes

       A character class allows a set(7,n,1 builtins) of possible characters, rather than just
       a single character, to match at a particular point in(1,8) a regex.  Charac-
       ter classes are denoted by brackets "[...]", with the set(7,n,1 builtins) of characters
       to be possibly matched inside.  Here are some examples:

           /cat/;            # matches 'cat'
           /[bcr]at/;        # matches 'bat', 'cat', or 'rat'
           "abc" =~ /[cab]/; # matches 'a'

       In the last statement, even though 'c' is the first character in(1,8) the
       class, the earliest point at which the regex(3,7) can match is 'a'.

           /[yY][eE][sS]/; # match 'yes' in(1,8) a case-insensitive way
                           # 'yes', 'Yes', 'YES', etc.
           /yes/i;         # also match 'yes' in(1,8) a case-insensitive way

       The last example shows a match with an 'i' modifier, which makes the
       match case-insensitive.

       Character classes also have ordinary and special characters, but the
       sets of ordinary and special characters inside a character class are
       different than those outside a character class.  The special characters
       for a character class are "-]\^$" and are matched using an escape:

          /[\]c]def/; # matches ']def' or 'cdef'
          $x = 'bcr';
          /[$x]at/;   # matches 'bat, 'cat', or 'rat'
          /[\$x]at/;  # matches '$at' or 'xat'
          /[\\$x]at/; # matches '\at', 'bat, 'cat', or 'rat'

       The special character '-' acts as a range operator within character
       classes, so that the unwieldy "[0123456789]" and "[]" become
       the svelte "[0-9]" and "[a-z]":

           /item[0-9]/;  # matches 'item0' or ... or 'item9'
           /[0-9a-fA-F]/;  # matches a hexadecimal digit

       If '-' is the first or last character in(1,8) a character class, it is
       treated as an ordinary character.

       The special character "^" in(1,8) the first position of a character class
       denotes a negated character class, which matches any character but
       those in(1,8) the brackets.  Both "[...]" and "[^...]" must match a charac-
       ter, or the match fails.  Then

           /[^a]at/;  # doesn't match 'aat' or 'at', but matches
                      # all other 'bat', 'cat, '0at', '%at', etc.
           /[^0-9]/;  # matches a non-numeric character
           /[a^]at/;  # matches 'aat' or '^at'; here '^' is ordinary

       Perl has several abbreviations for common character classes:

          \d is a digit and represents


          \s is a whitespace character and represents

               [\ \t\r\n\f]

          \w is a word character (alphanumeric or _) and represents


          \D is a negated \d; it represents any character but a digit


          \S is a negated \s; it represents any non-whitespace character


          \W is a negated \w; it represents any non-word character


          The period '.' matches any character but "\n"

       The "\d\s\w\D\S\W" abbreviations can be used both inside and outside of
       character classes.  Here are some in(1,8) use:

           /\d\d:\d\d:\d\d/; # matches a hh:mm:ss time(1,2,n) format
           /[\d\s]/;         # matches any digit or whitespace character
           /\w\W\w/;         # matches a word char, followed by a
                             # non-word char, followed by a word char
           /..rt/;           # matches any two chars, followed by 'rt'
           /end\./;          # matches 'end.'
           /end[.]/;         # same thing, matches 'end.'

       The word anchor  "\b" matches a boundary between a word character and a
       non-word character "\w\W" or "\W\w":

           $x = "Housecat catenates house and cat";
           $x =~ /\bcat/;  # matches cat in(1,8) 'catenates'
           $x =~ /cat\b/;  # matches cat in(1,8) 'housecat'
           $x =~ /\bcat\b/;  # matches 'cat' at end of string(3,n)

       In the last example, the end of the string(3,n) is considered a word bound-

       Matching this or that

       We can match different character strings with the alternation metachar-
       acter '|'.  To match "dog" or "cat", we form the regex(3,7) "dog|cat".  As
       before, perl will try to match the regex(3,7) at the earliest possible point
       in(1,8) the string.  At each character position, perl will first try to
       match the first alternative, "dog".  If "dog" doesn't match, perl will
       then try the next alternative, "cat".  If "cat" doesn't match either,
       then the match fails and perl moves to the next position in(1,8) the string.
       Some examples:

           "cats and dogs" =~ /cat|dog|bird/;  # matches "cat"
           "cats and dogs" =~ /dog|cat|bird/;  # matches "cat"

       Even though "dog" is the first alternative in(1,8) the second regex(3,7), "cat"
       is able to match earlier in(1,8) the string.

           "cats"          =~ /c|ca|cat|cats/; # matches "c"
           "cats"          =~ /cats|cat|ca|c/; # matches "cats"

       At a given character position, the first alternative that allows the
       regex(3,7) match to succeed will be the one that matches. Here, all the
       alternatives match at the first string(3,n) position, so the first matches.

       Grouping things and hierarchical matching

       The grouping metacharacters "()" allow a part of a regex(3,7) to be treated
       as a single unit.  Parts of a regex(3,7) are grouped by enclosing them in(1,8)
       parentheses.  The regex(3,7) "house(cat|keeper)" means match "house" fol-
       lowed by either "cat" or "keeper".  Some more examples are

           /(a|b)b/;    # matches 'ab' or 'bb'
           /(^a|b)c/;   # matches 'ac' at start of string(3,n) or 'bc' anywhere

           /house(cat|)/;  # matches either 'housecat' or 'house'
           /house(cat(s|)|)/;  # matches either 'housecats' or 'housecat' or
                               # 'house'.  Note groups can be nested.

           "20" =~ /(19|20|)\d\d/;  # matches the null alternative '()\d\d',
                                    # because '20\d\d' can't match

       Extracting matches

       The grouping metacharacters "()" also allow the extraction of the parts
       of a string(3,n) that matched.  For each grouping, the part that matched
       inside goes into the special variables $1, $2, etc.  They can be used
       just as ordinary variables:

           # extract hours, minutes, seconds
           $time(1,2,n) =~ /(\d\d):(\d\d):(\d\d)/;  # match hh:mm:ss format
           $hours = $1;
           $minutes = $2;
           $seconds = $3;

       In list context, a match "/regex(3,7)/" with groupings will return the list
       of matched values "($1,$2,...)".  So we could rewrite it as

           ($hours, $minutes, $second) = ($time(1,2,n) =~ /(\d\d):(\d\d):(\d\d)/);

       If the groupings in(1,8) a regex(3,7) are nested, $1 gets(3,n) the group with the
       leftmost opening parenthesis, $2 the next opening parenthesis, etc.
       For example, here is a complex regex(3,7) and the matching variables indi-
       cated below it:

            1  2      34

       Associated with the matching variables $1, $2, ... are the backrefer-
       ences "\1", "\2", ...  Backreferences are matching variables that can
       be used inside a regex:

           /(\w\w\w)\s\1/; # find sequences like 'the the' in(1,8) string(3,n)

       $1, $2, ... should only be used outside of a regex(3,7), and "\1", "\2", ...
       only inside a regex.

       Matching repetitions

       The quantifier metacharacters "?", "*", "+", and "{}" allow us to
       determine the number of repeats of a portion of a regex(3,7) we consider to
       be a match.  Quantifiers are put immediately after the character, char-
       acter class, or grouping that we want to specify.  They have the fol-
       lowing meanings:

          "a?" = match 'a' 1 or 0 times

          "a*" = match 'a' 0 or more times, i.e., any number of times

          "a+" = match 'a' 1 or more times, i.e., at least once

          "a{n,m}" = match at least "n" times, but not more than "m" times.

          "a{n,}" = match at least "n" or more times

          "a{n}" = match exactly "n" times

       Here are some examples:

           /[a-z]+\s+\d*/;  # match a lowercase word, at least some space, and
                            # any number of digits
           /(\w+)\s+\1/;    # match doubled words of arbitrary length
           $year =~ /\d{2,4}/;  # make sure year is at least 2 but not more
                                # than 4 digits
           $year =~ /\d{4}|\d{2}/;    # better match; throw out 3 digit dates

       These quantifiers will try to match as much of the string(3,n) as possible,
       while still allowing the regex(3,7) to match.  So we have

           $x = 'the cat in(1,8) the hat';
           $x =~ /^(.*)(at)(.*)$/; # matches,
                                   # $1 = 'the cat in(1,8) the h'
                                   # $2 = 'at'
                                   # $3 = ''   (0 matches)

       The first quantifier ".*" grabs as much of the string(3,n) as possible while
       still having the regex(3,7) match. The second quantifier ".*" has no string(3,n)
       left to it, so it matches 0 times.

       More matching

       There are a few more things you might want to know about matching oper-
       ators.  In the code

           $pattern = 'Seuss';
           while (<>) {
               print if(3,n) /$pattern/;

       perl has to re-evaluate $pattern each time(1,2,n) through the loop.  If $pat-
       tern won't be changing, use the "//o" modifier, to only perform vari-
       able substitutions once.  If you don't want any substitutions at all,
       use the special delimiter "m''":

           @pattern = ('Seuss');
           m/@pattern/; # matches 'Seuss'
           m'@pattern'; # matches the literal string(3,n) '@pattern'

       The global modifier "//g" allows the matching operator to match within
       a string(3,n) as many times as possible.  In scalar context, successive
       matches against a string(3,n) will have "//g" jump from match to match,
       keeping track of position in(1,8) the string(3,n) as it goes along.  You can get
       or set(7,n,1 builtins) the position with the "pos()" function.  For example,

           $x = "cat dog house"; # 3 words
           while ($x =~ /(\w+)/g) {
               print "Word is $1, ends at position ", pos $x, "\n";


           Word is cat, ends at position 3
           Word is dog, ends at position 7
           Word is house, ends at position 13

       A failed match or changing the target string(3,n) resets the position.  If
       you don't want the position reset(1,7,1 tput) after failure to match, add the
       "//c", as in(1,8) "/regex(3,7)/gc".

       In list context, "//g" returns a list of matched groupings, or if(3,n) there
       are no groupings, a list of matches to the whole regex.  So

           @words = ($x =~ /(\w+)/g);  # matches,
                                       # $word[0] = 'cat'
                                       # $word[1] = 'dog'
                                       # $word[2] = 'house'

       Search and replace

       Search and replace is performed using "s/regex(3,7)/replacement/modifiers".
       The "replacement" is a Perl double quoted string(3,n) that replaces in(1,8) the
       string(3,n) whatever is matched with the "regex(3,7)".  The operator "=~" is also
       used here to associate a string(3,n) with "s///".  If matching against $_,
       the "$_ =~"  can be dropped.  If there is a match, "s///" returns the
       number of substitutions made, otherwise it returns false.  Here are a
       few examples:

           $x = "Time to feed the cat!";
           $x =~ s/cat/hacker/;   # $x contains "Time to feed the hacker!"
           $y = "'quoted words'";
           $y =~ s/^'(.*)'$/$1/;  # strip single quotes,
                                  # $y contains "quoted words"

       With the "s///" operator, the matched variables $1, $2, etc.  are imme-
       diately available for use in(1,8) the replacement expression. With the
       global modifier, "s///g" will search and replace all occurrences of the
       regex(3,7) in(1,8) the string:

           $x = "I batted 4 for 4";
           $x =~ s/4/four/;   # $x contains "I batted four for 4"
           $x = "I batted 4 for 4";
           $x =~ s/4/four/g;  # $x contains "I batted four for four"

       The evaluation modifier "s///e" wraps an "eval{...}" around the
       replacement string(3,n) and the evaluated result is substituted for the
       matched substring.  Some examples:

           # reverse all the words in(1,8) a string(3,n)
           $x = "the cat in(1,8) the hat";
           $x =~ s/(\w+)/reverse $1/ge;   # $x contains "eht tac ni eht tah"

           # convert percentage to decimal
           $x = "A 39% hit rate";
           $x =~ s!(\d+)%!$1/100!e;       # $x contains "A 0.39 hit rate"

       The last example shows that "s///" can use other delimiters, such as
       "s!!!" and "s{}{}", and even "s{}//".  If single quotes are used
       "s'''", then the regex(3,7) and replacement are treated as single quoted

       The split(1,n) operator

       "split(1,n) /regex(3,7)/, string(3,n)" splits "string(3,n)" into a list of substrings and
       returns that list.  The regex(3,7) determines the character sequence that
       "string(3,n)" is split(1,n) with respect to.  For example, to split(1,n) a string(3,n) into
       words, use

           $x = "Calvin and Hobbes";
           @word = split(1,n) /\s+/, $x;  # $word[0] = 'Calvin'
                                     # $word[1] = 'and'
                                     # $word[2] = 'Hobbes'

       To extract a comma-delimited list of numbers, use

           $x = "1.618,2.718,   3.142";
           @const = split(1,n) /,\s*/, $x;  # $const[0] = '1.618'
                                       # $const[1] = '2.718'
                                       # $const[2] = '3.142'

       If the empty regex(3,7) "//" is used, the string(3,n) is split(1,n) into individual
       characters.  If the regex(3,7) has groupings, then the list produced con-
       tains the matched substrings from the groupings as well:

           $x = "/usr/bin";
           @parts = split(1,n) m!(/)!, $x;  # $parts[0] = ''
                                       # $parts[1] = '/'
                                       # $parts[2] = 'usr'
                                       # $parts[3] = '/'
                                       # $parts[4] = 'bin'

       Since the first character of $x matched the regex(3,7), "split(1,n)" prepended an
       empty initial element to the list.


       This is just a quick start guide.  For a more in-depth tutorial on
       regexes, see perlretut and for the reference page, see perlre.

       Copyright (c) 2000 Mark Kvale All rights reserved.

       This document may be distributed under the same terms as Perl itself.


       The author would like to thank Mark-Jason Dominus, Tom Christiansen,
       Ilya Zakharevich, Brad Hughes, and Mike Giroux for all their helpful

perl v5.8.5                       2004-04-23                    PERLREQUICK(1)

References for this manual (incoming links)