Plan 9 from Bell Labs’s /usr/web/sources/contrib/gabidiaz/root/sys/man/1perl/perlrequick

Copyright © 2021 Plan 9 Foundation.
Distributed under the MIT License.
Download the Plan 9 distribution.


.\" Automatically generated by Pod::Man v1.34, Pod::Parser v1.13
.\"
.\" Standard preamble:
.\" ========================================================================
.de Sh \" Subsection heading
.br
.if t .Sp
.ne 5
.PP
\fB\\$1\fR
.PP
..
.de Sp \" Vertical space (when we can't use .PP)
.if t .sp .5v
.if n .sp
..
.de Vb \" Begin verbatim text
.ft CW
.nf
.ne \\$1
..
.de Ve \" End verbatim text
.ft R
.fi
..
.\" Set up some character translations and predefined strings.  \*(-- will
.\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left
.\" double quote, and \*(R" will give a right double quote.  | will give a
.\" real vertical bar.  \*(C+ will give a nicer C++.  Capital omega is used to
.\" do unbreakable dashes and therefore won't be available.  \*(C` and \*(C'
.\" expand to `' in nroff, nothing in troff, for use with C<>.
.tr \(*W-|\(bv\*(Tr
.ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p'
.ie n \{\
.    ds -- \(*W-
.    ds PI pi
.    if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
.    if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\"  diablo 12 pitch
.    ds L" ""
.    ds R" ""
.    ds C` ""
.    ds C' ""
'br\}
.el\{\
.    ds -- \|\(em\|
.    ds PI \(*p
.    ds L" ``
.    ds R" ''
'br\}
.\"
.\" If the F register is turned on, we'll generate index entries on stderr for
.\" titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and index
.\" entries marked with X<> in POD.  Of course, you'll have to process the
.\" output yourself in some meaningful fashion.
.if \nF \{\
.    de IX
.    tm Index:\\$1\t\\n%\t"\\$2"
..
.    nr % 0
.    rr F
.\}
.\"
.\" For nroff, turn off justification.  Always turn off hyphenation; it makes
.\" way too many mistakes in technical documents.
.hy 0
.if n .na
.\"
.\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2).
.\" Fear.  Run.  Save yourself.  No user-serviceable parts.
.    \" fudge factors for nroff and troff
.if n \{\
.    ds #H 0
.    ds #V .8m
.    ds #F .3m
.    ds #[ \f1
.    ds #] \fP
.\}
.if t \{\
.    ds #H ((1u-(\\\\n(.fu%2u))*.13m)
.    ds #V .6m
.    ds #F 0
.    ds #[ \&
.    ds #] \&
.\}
.    \" simple accents for nroff and troff
.if n \{\
.    ds ' \&
.    ds ` \&
.    ds ^ \&
.    ds , \&
.    ds ~ ~
.    ds /
.\}
.if t \{\
.    ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u"
.    ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u'
.    ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u'
.    ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u'
.    ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u'
.    ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u'
.\}
.    \" troff and (daisy-wheel) nroff accents
.ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V'
.ds 8 \h'\*(#H'\(*b\h'-\*(#H'
.ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#]
.ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H'
.ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u'
.ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#]
.ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#]
.ds ae a\h'-(\w'a'u*4/10)'e
.ds Ae A\h'-(\w'A'u*4/10)'E
.    \" corrections for vroff
.if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u'
.if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u'
.    \" for low resolution devices (crt and lpr)
.if \n(.H>23 .if \n(.V>19 \
\{\
.    ds : e
.    ds 8 ss
.    ds o a
.    ds d- d\h'-1'\(ga
.    ds D- D\h'-1'\(hy
.    ds th \o'bp'
.    ds Th \o'LP'
.    ds ae ae
.    ds Ae AE
.\}
.rm #[ #] #H #V #F C
.\" ========================================================================
.\"
.IX Title "PERLREQUICK 1"
.TH PERLREQUICK 1 "2002-11-24" "perl v5.8.0" "Perl Programmers Reference Guide"
.SH "NAME"
perlrequick \- Perl regular expressions quick start
.SH "DESCRIPTION"
.IX Header "DESCRIPTION"
This page covers the very basics of understanding, creating and
using regular expressions ('regexes') in Perl.
.SH "The Guide"
.IX Header "The Guide"
.Sh "Simple word matching"
.IX Subsection "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:
.PP
.Vb 1
\&    "Hello World" =~ /World/;  # matches
.Ve
.PP
In this statement, \f(CW\*(C`World\*(C'\fR is a regex and the \f(CW\*(C`//\*(C'\fR enclosing
\&\f(CW\*(C`/World/\*(C'\fR tells perl to search a string for a match.  The operator
\&\f(CW\*(C`=~\*(C'\fR 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, \f(CW\*(C`World\*(C'\fR matches the second word in \f(CW"Hello World"\fR, so the
expression is true.  This idea has several variations.
.PP
Expressions like this are useful in conditionals:
.PP
.Vb 1
\&    print "It matches\en" if "Hello World" =~ /World/;
.Ve
.PP
The sense of the match can be reversed by using \f(CW\*(C`!~\*(C'\fR operator:
.PP
.Vb 1
\&    print "It doesn't match\en" if "Hello World" !~ /World/;
.Ve
.PP
The literal string in the regex can be replaced by a variable:
.PP
.Vb 2
\&    $greeting = "World";
\&    print "It matches\en" if "Hello World" =~ /$greeting/;
.Ve
.PP
If you're matching against \f(CW$_\fR, the \f(CW\*(C`$_ =~\*(C'\fR part can be omitted:
.PP
.Vb 2
\&    $_ = "Hello World";
\&    print "It matches\en" if /World/;
.Ve
.PP
Finally, the \f(CW\*(C`//\*(C'\fR default delimiters for a match can be changed to
arbitrary delimiters by putting an \f(CW'm'\fR out front:
.PP
.Vb 4
\&    "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
.Ve
.PP
Regexes must match a part of the string \fIexactly\fR in order for the
statement to be true:
.PP
.Vb 3
\&    "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
.Ve
.PP
perl will always match at the earliest possible point in the string:
.PP
.Vb 2
\&    "Hello World" =~ /o/;       # matches 'o' in 'Hello'
\&    "That hat is red" =~ /hat/; # matches 'hat' in 'That'
.Ve
.PP
Not all characters can be used 'as is' in a match.  Some characters,
called \fBmetacharacters\fR, are reserved for use in regex notation.
The metacharacters are
.PP
.Vb 1
\&    {}[]()^$.|*+?\e
.Ve
.PP
A metacharacter can be matched by putting a backslash before it:
.PP
.Vb 4
\&    "2+2=4" =~ /2+2/;    # doesn't match, + is a metacharacter
\&    "2+2=4" =~ /2\e+2/;   # matches, \e+ is treated like an ordinary +
\&    'C:\eWIN32' =~ /C:\e\eWIN/;                       # matches
\&    "/usr/bin/perl" =~ /\e/usr\e/local\e/bin\e/perl/;  # matches
.Ve
.PP
In the last regex, the forward slash \f(CW'/'\fR is also backslashed,
because it is used to delimit the regex.
.PP
Non-printable \s-1ASCII\s0 characters are represented by \fBescape sequences\fR.
Common examples are \f(CW\*(C`\et\*(C'\fR for a tab, \f(CW\*(C`\en\*(C'\fR for a newline, and \f(CW\*(C`\er\*(C'\fR
for a carriage return.  Arbitrary bytes are represented by octal
escape sequences, e.g., \f(CW\*(C`\e033\*(C'\fR, or hexadecimal escape sequences,
e.g., \f(CW\*(C`\ex1B\*(C'\fR:
.PP
.Vb 2
\&    "1000\et2000" =~ m(0\et2)        # matches
\&    "cat"        =~ /\e143\ex61\ex74/ # matches, but a weird way to spell cat
.Ve
.PP
Regexes are treated mostly as double quoted strings, so variable
substitution works:
.PP
.Vb 3
\&    $foo = 'house';
\&    'cathouse' =~ /cat$foo/;   # matches
\&    'housecat' =~ /${foo}cat/; # matches
.Ve
.PP
With all of the regexes above, if the regex matched anywhere in the
string, it was considered a match.  To specify \fIwhere\fR it should
match, we would use the \fBanchor\fR metacharacters \f(CW\*(C`^\*(C'\fR and \f(CW\*(C`$\*(C'\fR.  The
anchor \f(CW\*(C`^\*(C'\fR means match at the beginning of the string and the anchor
\&\f(CW\*(C`$\*(C'\fR means match at the end of the string, or before a newline at the
end of the string.  Some examples:
.PP
.Vb 5
\&    "housekeeper" =~ /keeper/;         # matches
\&    "housekeeper" =~ /^keeper/;        # doesn't match
\&    "housekeeper" =~ /keeper$/;        # matches
\&    "housekeeper\en" =~ /keeper$/;      # matches
\&    "housekeeper" =~ /^housekeeper$/;  # matches
.Ve
.Sh "Using character classes"
.IX Subsection "Using character classes"
A \fBcharacter class\fR allows a set of possible characters, rather than
just a single character, to match at a particular point in a regex.
Character classes are denoted by brackets \f(CW\*(C`[...]\*(C'\fR, with the set of
characters to be possibly matched inside.  Here are some examples:
.PP
.Vb 3
\&    /cat/;            # matches 'cat'
\&    /[bcr]at/;        # matches 'bat', 'cat', or 'rat'
\&    "abc" =~ /[cab]/; # matches 'a'
.Ve
.PP
In the last statement, even though \f(CW'c'\fR is the first character in
the class, the earliest point at which the regex can match is \f(CW'a'\fR.
.PP
.Vb 3
\&    /[yY][eE][sS]/; # match 'yes' in a case-insensitive way
\&                    # 'yes', 'Yes', 'YES', etc.
\&    /yes/i;         # also match 'yes' in a case-insensitive way
.Ve
.PP
The last example shows a match with an \f(CW'i'\fR \fBmodifier\fR, which makes
the match case\-insensitive.
.PP
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 \f(CW\*(C`\-]\e^$\*(C'\fR and are matched using an
escape:
.PP
.Vb 5
\&   /[\e]c]def/; # matches ']def' or 'cdef'
\&   $x = 'bcr';
\&   /[$x]at/;   # matches 'bat, 'cat', or 'rat'
\&   /[\e$x]at/;  # matches '$at' or 'xat'
\&   /[\e\e$x]at/; # matches '\eat', 'bat, 'cat', or 'rat'
.Ve
.PP
The special character \f(CW'\-'\fR acts as a range operator within character
classes, so that the unwieldy \f(CW\*(C`[0123456789]\*(C'\fR and \f(CW\*(C`[abc...xyz]\*(C'\fR
become the svelte \f(CW\*(C`[0\-9]\*(C'\fR and \f(CW\*(C`[a\-z]\*(C'\fR:
.PP
.Vb 2
\&    /item[0-9]/;  # matches 'item0' or ... or 'item9'
\&    /[0-9a-fA-F]/;  # matches a hexadecimal digit
.Ve
.PP
If \f(CW'\-'\fR is the first or last character in a character class, it is
treated as an ordinary character.
.PP
The special character \f(CW\*(C`^\*(C'\fR in the first position of a character class
denotes a \fBnegated character class\fR, which matches any character but
those in the brackets.  Both \f(CW\*(C`[...]\*(C'\fR and \f(CW\*(C`[^...]\*(C'\fR must match a
character, or the match fails.  Then
.PP
.Vb 4
\&    /[^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
.Ve
.PP
Perl has several abbreviations for common character classes:
.IP "\(bu" 4
\&\ed is a digit and represents [0\-9]
.IP "\(bu" 4
\&\es is a whitespace character and represents [\e \et\er\en\ef]
.IP "\(bu" 4
\&\ew is a word character (alphanumeric or _) and represents [0\-9a\-zA\-Z_]
.IP "\(bu" 4
\&\eD is a negated \ed; it represents any character but a digit [^0\-9]
.IP "\(bu" 4
\&\eS is a negated \es; it represents any non-whitespace character [^\es]
.IP "\(bu" 4
\&\eW is a negated \ew; it represents any non-word character [^\ew]
.IP "\(bu" 4
The period '.' matches any character but \*(L"\en\*(R"
.PP
The \f(CW\*(C`\ed\es\ew\eD\eS\eW\*(C'\fR abbreviations can be used both inside and outside
of character classes.  Here are some in use:
.PP
.Vb 7
\&    /\ed\ed:\ed\ed:\ed\ed/; # matches a hh:mm:ss time format
\&    /[\ed\es]/;         # matches any digit or whitespace character
\&    /\ew\eW\ew/;         # matches a word char, followed by a
\&                      # non-word char, followed by a word char
\&    /..rt/;           # matches any two chars, followed by 'rt'
\&    /end\e./;          # matches 'end.'
\&    /end[.]/;         # same thing, matches 'end.'
.Ve
.PP
The \fBword\ anchor\fR\  \f(CW\*(C`\eb\*(C'\fR matches a boundary between a word
character and a non-word character \f(CW\*(C`\ew\eW\*(C'\fR or \f(CW\*(C`\eW\ew\*(C'\fR:
.PP
.Vb 4
\&    $x = "Housecat catenates house and cat";
\&    $x =~ /\ebcat/;  # matches cat in 'catenates'
\&    $x =~ /cat\eb/;  # matches cat in 'housecat'
\&    $x =~ /\ebcat\eb/;  # matches 'cat' at end of string
.Ve
.PP
In the last example, the end of the string is considered a word
boundary.
.Sh "Matching this or that"
.IX Subsection "Matching this or that"
We can match different character strings with the \fBalternation\fR
metacharacter \f(CW'|'\fR.  To match \f(CW\*(C`dog\*(C'\fR or \f(CW\*(C`cat\*(C'\fR, we form the regex
\&\f(CW\*(C`dog|cat\*(C'\fR.  As before, perl will try to match the regex at the
earliest possible point in the string.  At each character position,
perl will first try to match the first alternative, \f(CW\*(C`dog\*(C'\fR.  If
\&\f(CW\*(C`dog\*(C'\fR doesn't match, perl will then try the next alternative, \f(CW\*(C`cat\*(C'\fR.
If \f(CW\*(C`cat\*(C'\fR doesn't match either, then the match fails and perl moves to
the next position in the string.  Some examples:
.PP
.Vb 2
\&    "cats and dogs" =~ /cat|dog|bird/;  # matches "cat"
\&    "cats and dogs" =~ /dog|cat|bird/;  # matches "cat"
.Ve
.PP
Even though \f(CW\*(C`dog\*(C'\fR is the first alternative in the second regex,
\&\f(CW\*(C`cat\*(C'\fR is able to match earlier in the string.
.PP
.Vb 2
\&    "cats"          =~ /c|ca|cat|cats/; # matches "c"
\&    "cats"          =~ /cats|cat|ca|c/; # matches "cats"
.Ve
.PP
At a given character position, the first alternative that allows the
regex match to succeed will be the one that matches. Here, all the
alternatives match at the first string position, so th first matches.
.Sh "Grouping things and hierarchical matching"
.IX Subsection "Grouping things and hierarchical matching"
The \fBgrouping\fR metacharacters \f(CW\*(C`()\*(C'\fR allow a part of a regex to be
treated as a single unit.  Parts of a regex are grouped by enclosing
them in parentheses.  The regex \f(CW\*(C`house(cat|keeper)\*(C'\fR means match
\&\f(CW\*(C`house\*(C'\fR followed by either \f(CW\*(C`cat\*(C'\fR or \f(CW\*(C`keeper\*(C'\fR.  Some more examples
are
.PP
.Vb 2
\&    /(a|b)b/;    # matches 'ab' or 'bb'
\&    /(^a|b)c/;   # matches 'ac' at start of string or 'bc' anywhere
.Ve
.PP
.Vb 3
\&    /house(cat|)/;  # matches either 'housecat' or 'house'
\&    /house(cat(s|)|)/;  # matches either 'housecats' or 'housecat' or
\&                        # 'house'.  Note groups can be nested.
.Ve
.PP
.Vb 2
\&    "20" =~ /(19|20|)\ed\ed/;  # matches the null alternative '()\ed\ed',
\&                             # because '20\ed\ed' can't match
.Ve
.Sh "Extracting matches"
.IX Subsection "Extracting matches"
The grouping metacharacters \f(CW\*(C`()\*(C'\fR also allow the extraction of the
parts of a string that matched.  For each grouping, the part that
matched inside goes into the special variables \f(CW$1\fR, \f(CW$2\fR, etc.
They can be used just as ordinary variables:
.PP
.Vb 5
\&    # extract hours, minutes, seconds
\&    $time =~ /(\ed\ed):(\ed\ed):(\ed\ed)/;  # match hh:mm:ss format
\&    $hours = $1;
\&    $minutes = $2;
\&    $seconds = $3;
.Ve
.PP
In list context, a match \f(CW\*(C`/regex/\*(C'\fR with groupings will return the
list of matched values \f(CW\*(C`($1,$2,...)\*(C'\fR.  So we could rewrite it as
.PP
.Vb 1
\&    ($hours, $minutes, $second) = ($time =~ /(\ed\ed):(\ed\ed):(\ed\ed)/);
.Ve
.PP
If the groupings in a regex are nested, \f(CW$1\fR gets the group with the
leftmost opening parenthesis, \f(CW$2\fR the next opening parenthesis,
etc.  For example, here is a complex regex and the matching variables
indicated below it:
.PP
.Vb 2
\&    /(ab(cd|ef)((gi)|j))/;
\&     1  2      34
.Ve
.PP
Associated with the matching variables \f(CW$1\fR, \f(CW$2\fR, ... are
the \fBbackreferences\fR \f(CW\*(C`\e1\*(C'\fR, \f(CW\*(C`\e2\*(C'\fR, ...  Backreferences are
matching variables that can be used \fIinside\fR a regex:
.PP
.Vb 1
\&    /(\ew\ew\ew)\es\e1/; # find sequences like 'the the' in string
.Ve
.PP
\&\f(CW$1\fR, \f(CW$2\fR, ... should only be used outside of a regex, and \f(CW\*(C`\e1\*(C'\fR,
\&\f(CW\*(C`\e2\*(C'\fR, ... only inside a regex.
.Sh "Matching repetitions"
.IX Subsection "Matching repetitions"
The \fBquantifier\fR metacharacters \f(CW\*(C`?\*(C'\fR, \f(CW\*(C`*\*(C'\fR, \f(CW\*(C`+\*(C'\fR, and \f(CW\*(C`{}\*(C'\fR allow us
to determine the number of repeats of a portion of a regex we
consider to be a match.  Quantifiers are put immediately after the
character, character class, or grouping that we want to specify.  They
have the following meanings:
.IP "\(bu" 4
\&\f(CW\*(C`a?\*(C'\fR = match 'a' 1 or 0 times
.IP "\(bu" 4
\&\f(CW\*(C`a*\*(C'\fR = match 'a' 0 or more times, i.e., any number of times
.IP "\(bu" 4
\&\f(CW\*(C`a+\*(C'\fR = match 'a' 1 or more times, i.e., at least once
.IP "\(bu" 4
\&\f(CW\*(C`a{n,m}\*(C'\fR = match at least \f(CW\*(C`n\*(C'\fR times, but not more than \f(CW\*(C`m\*(C'\fR
times.
.IP "\(bu" 4
\&\f(CW\*(C`a{n,}\*(C'\fR = match at least \f(CW\*(C`n\*(C'\fR or more times
.IP "\(bu" 4
\&\f(CW\*(C`a{n}\*(C'\fR = match exactly \f(CW\*(C`n\*(C'\fR times
.PP
Here are some examples:
.PP
.Vb 6
\&    /[a-z]+\es+\ed*/;  # match a lowercase word, at least some space, and
\&                     # any number of digits
\&    /(\ew+)\es+\e1/;    # match doubled words of arbitrary length
\&    $year =~ /\ed{2,4}/;  # make sure year is at least 2 but not more
\&                         # than 4 digits
\&    $year =~ /\ed{4}|\ed{2}/;    # better match; throw out 3 digit dates
.Ve
.PP
These quantifiers will try to match as much of the string as possible,
while still allowing the regex to match.  So we have
.PP
.Vb 5
\&    $x = 'the cat in the hat';
\&    $x =~ /^(.*)(at)(.*)$/; # matches,
\&                            # $1 = 'the cat in the h'
\&                            # $2 = 'at'
\&                            # $3 = ''   (0 matches)
.Ve
.PP
The first quantifier \f(CW\*(C`.*\*(C'\fR grabs as much of the string as possible
while still having the regex match. The second quantifier \f(CW\*(C`.*\*(C'\fR has
no string left to it, so it matches 0 times.
.Sh "More matching"
.IX Subsection "More matching"
There are a few more things you might want to know about matching
operators.  In the code
.PP
.Vb 4
\&    $pattern = 'Seuss';
\&    while (<>) {
\&        print if /$pattern/;
\&    }
.Ve
.PP
perl has to re-evaluate \f(CW$pattern\fR each time through the loop.  If
\&\f(CW$pattern\fR won't be changing, use the \f(CW\*(C`//o\*(C'\fR modifier, to only
perform variable substitutions once.  If you don't want any
substitutions at all, use the special delimiter \f(CW\*(C`m''\*(C'\fR:
.PP
.Vb 2
\&    $pattern = 'Seuss';
\&    m'$pattern'; # matches '$pattern', not 'Seuss'
.Ve
.PP
The global modifier \f(CW\*(C`//g\*(C'\fR allows the matching operator to match
within a string as many times as possible.  In scalar context,
successive matches against a string will have \f(CW\*(C`//g\*(C'\fR jump from match
to match, keeping track of position in the string as it goes along.
You can get or set the position with the \f(CW\*(C`pos()\*(C'\fR function.
For example,
.PP
.Vb 4
\&    $x = "cat dog house"; # 3 words
\&    while ($x =~ /(\ew+)/g) {
\&        print "Word is $1, ends at position ", pos $x, "\en";
\&    }
.Ve
.PP
prints
.PP
.Vb 3
\&    Word is cat, ends at position 3
\&    Word is dog, ends at position 7
\&    Word is house, ends at position 13
.Ve
.PP
A failed match or changing the target string resets the position.  If
you don't want the position reset after failure to match, add the
\&\f(CW\*(C`//c\*(C'\fR, as in \f(CW\*(C`/regex/gc\*(C'\fR.
.PP
In list context, \f(CW\*(C`//g\*(C'\fR returns a list of matched groupings, or if
there are no groupings, a list of matches to the whole regex.  So
.PP
.Vb 4
\&    @words = ($x =~ /(\ew+)/g);  # matches,
\&                                # $word[0] = 'cat'
\&                                # $word[1] = 'dog'
\&                                # $word[2] = 'house'
.Ve
.Sh "Search and replace"
.IX Subsection "Search and replace"
Search and replace is performed using \f(CW\*(C`s/regex/replacement/modifiers\*(C'\fR.
The \f(CW\*(C`replacement\*(C'\fR is a Perl double quoted string that replaces in the
string whatever is matched with the \f(CW\*(C`regex\*(C'\fR.  The operator \f(CW\*(C`=~\*(C'\fR is
also used here to associate a string with \f(CW\*(C`s///\*(C'\fR.  If matching
against \f(CW$_\fR, the \f(CW\*(C`$_\ =~\*(C'\fR\  can be dropped.  If there is a match,
\&\f(CW\*(C`s///\*(C'\fR returns the number of substitutions made, otherwise it returns
false.  Here are a few examples:
.PP
.Vb 5
\&    $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"
.Ve
.PP
With the \f(CW\*(C`s///\*(C'\fR operator, the matched variables \f(CW$1\fR, \f(CW$2\fR, etc.
are immediately available for use in the replacement expression. With
the global modifier, \f(CW\*(C`s///g\*(C'\fR will search and replace all occurrences
of the regex in the string:
.PP
.Vb 4
\&    $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"
.Ve
.PP
The evaluation modifier \f(CW\*(C`s///e\*(C'\fR wraps an \f(CW\*(C`eval{...}\*(C'\fR around the
replacement string and the evaluated result is substituted for the
matched substring.  Some examples:
.PP
.Vb 3
\&    # reverse all the words in a string
\&    $x = "the cat in the hat";
\&    $x =~ s/(\ew+)/reverse $1/ge;   # $x contains "eht tac ni eht tah"
.Ve
.PP
.Vb 3
\&    # convert percentage to decimal
\&    $x = "A 39% hit rate";
\&    $x =~ s!(\ed+)%!$1/100!e;       # $x contains "A 0.39 hit rate"
.Ve
.PP
The last example shows that \f(CW\*(C`s///\*(C'\fR can use other delimiters, such as
\&\f(CW\*(C`s!!!\*(C'\fR and \f(CW\*(C`s{}{}\*(C'\fR, and even \f(CW\*(C`s{}//\*(C'\fR.  If single quotes are used
\&\f(CW\*(C`s'''\*(C'\fR, then the regex and replacement are treated as single quoted
strings.
.Sh "The split operator"
.IX Subsection "The split operator"
\&\f(CW\*(C`split /regex/, string\*(C'\fR splits \f(CW\*(C`string\*(C'\fR into a list of substrings
and returns that list.  The regex determines the character sequence
that \f(CW\*(C`string\*(C'\fR is split with respect to.  For example, to split a
string into words, use
.PP
.Vb 4
\&    $x = "Calvin and Hobbes";
\&    @word = split /\es+/, $x;  # $word[0] = 'Calvin'
\&                              # $word[1] = 'and'
\&                              # $word[2] = 'Hobbes'
.Ve
.PP
To extract a comma-delimited list of numbers, use
.PP
.Vb 4
\&    $x = "1.618,2.718,   3.142";
\&    @const = split /,\es*/, $x;  # $const[0] = '1.618'
\&                                # $const[1] = '2.718'
\&                                # $const[2] = '3.142'
.Ve
.PP
If the empty regex \f(CW\*(C`//\*(C'\fR is used, the string is split into individual
characters.  If the regex has groupings, then list produced contains
the matched substrings from the groupings as well:
.PP
.Vb 6
\&    $x = "/usr/bin";
\&    @parts = split m!(/)!, $x;  # $parts[0] = ''
\&                                # $parts[1] = '/'
\&                                # $parts[2] = 'usr'
\&                                # $parts[3] = '/'
\&                                # $parts[4] = 'bin'
.Ve
.PP
Since the first character of \f(CW$x\fR matched the regex, \f(CW\*(C`split\*(C'\fR prepended
an empty initial element to the list.
.SH "BUGS"
.IX Header "BUGS"
None.
.SH "SEE ALSO"
.IX Header "SEE ALSO"
This is just a quick start guide.  For a more in-depth tutorial on
regexes, see perlretut and for the reference page, see perlre.
.SH "AUTHOR AND COPYRIGHT"
.IX Header "AUTHOR AND COPYRIGHT"
Copyright (c) 2000 Mark Kvale
All rights reserved.
.PP
This document may be distributed under the same terms as Perl itself.
.Sh "Acknowledgments"
.IX Subsection "Acknowledgments"
The author would like to thank Mark-Jason Dominus, Tom Christiansen,
Ilya Zakharevich, Brad Hughes, and Mike Giroux for all their helpful
comments.

Bell Labs OSI certified Powered by Plan 9

(Return to Plan 9 Home Page)

Copyright © 2021 Plan 9 Foundation. All Rights Reserved.
Comments to webmaster@9p.io.