matches a chunk of non-parentheses, possibly included in parentheses
themselves.
(?imsx-imsx)
One or more embedded pattern-match modifiers. This is particularly useful
for patterns that are specified in a table somewhere, some of which want to be
case sensitive, and some of which don't. The case insensitive ones need to
include merely (?i) at the front of the pattern. For example:
$pattern = "foobar";
if ( /$pattern/i ) { }
# more flexible:
$pattern = "(?i)foobar";
if ( /$pattern/ ) { }
Letters after - switch modifiers off.
These modifiers are localized inside an enclosing group (if any). Say,
( (?i) blah ) s+ 1
(assuming x modifier, and no i modifier outside
of this group) will match a repeated (including the case!) word
blah in any case.
A question mark was chosen for this and for the new
minimal-matching construct because 1) question mark is pretty rare in older
regular expressions, and 2) whenever you see one, you should stop and
``question'' exactly what is going on. That's psychology...
Backtracking
A fundamental feature of regular expression matching
involves the notion called backtracking, which is currently used (when
needed) by all regular expression quantifiers, namely *,
*?, +, +?, {n,m}, and
{n,m}?.
For a regular expression to match, the entire regular expression
must match, not just part of it. So if the beginning of a pattern containing a
quantifier succeeds in a way that causes later parts in the pattern to fail, the
matching engine backs up and recalculates the beginning part--that's why it's
called backtracking.
Here is an example of backtracking: Let's say you want to find the word
following ``foo'' in the string ``Food is on the foo table.'':
$_ = "Food is on the foo table.";
if ( /b(foo)s+(w+)/i ) {
print "$2 follows $1.n";
}
When the match runs, the first part of the regular expression
(b(foo)) finds a possible match right at the beginning of the
string, and loads up $1 with ``Foo''. However, as soon as the
matching engine sees that there's no whitespace following the ``Foo'' that it
had saved in $1, it realizes its mistake and starts over again one character
after where it had the tentative match. This time it goes all the way until the
next occurrence of ``foo''. The complete regular expression matches this time,
and you get the expected output of ``table follows foo.''
Sometimes minimal matching can help a lot. Imagine you'd like to match
everything between ``foo'' and ``bar''. Initially, you write something like
this:
$_ = "The food is under the bar in the barn.";
if ( /foo(.*)bar/ ) {
print "got <$1>n";
}
Which perhaps unexpectedly yields:
got <d is under the bar in the >
That's because .* was greedy, so you get everything between the
first ``foo'' and the last ``bar''. In this case, it's more
effective to use minimal matching to make sure you get the text between a
``foo'' and the first ``bar'' thereafter.
if ( /foo(.*?)bar/ ) { print "got <$1>n" }
got <d is under the >
Here's another example: let's say you'd like to match a number at the end of
a string, and you also want to keep the preceding part the match. So you write
this:
$_ = "I have 2 numbers: 53147";
if ( /(.*)(d*)/ ) { # Wrong!
print "Beginning is <$1>, number is <$2>.n";
}
That won't work at all, because .* was greedy and gobbled up the
whole string. As d* can match on an empty string the complete
regular expression matched successfully.
Beginning is <I have 2 numbers: 53147>, number is <>.
Here are some variants, most of which don't work:
$_ = "I have 2 numbers: 53147";
@pats = qw{
(.*)(d*)
(.*)(d+)
(.*?)(d*)
(.*?)(d+)
(.*)(d+)$
(.*?)(d+)$
(.*)b(d+)$
(.*D)(d+)$
};
for $pat (@pats) {
printf "%-12s ", $pat;
if ( /$pat/ ) {
print "<$1> <$2>n";
} else {
print "FAILn";
}
}
That will print out:
(.*)(d*) <I have 2 numbers: 53147> <>
(.*)(d+) <I have 2 numbers: 5314> <7>
(.*?)(d*) <> <>
(.*?)(d+) <I have > <2>
(.*)(d+)$ <I have 2 numbers: 5314> <7>
(.*?)(d+)$ <I have 2 numbers: > <53147>
(.*)b(d+)$ <I have 2 numbers: > <53147>
(.*D)(d+)$ <I have 2 numbers: > <53147>
As you see, this can be a bit tricky. It's important to realize that a
regular expression is merely a set of assertions that gives a definition of
success. There may be 0, 1, or several different ways that the definition might
succeed against a particular string. And if there are multiple ways it might
succeed, you need to understand backtracking to know which variety of success
you will achieve.
When using lookahead assertions and negations, this can all get even tricker.
Imagine you'd like to find a sequence of non-digits not followed by ``123''. You
might try to write that as
$_ = "ABC123";
if ( /^D*(?!123)/ ) { # Wrong!
print "Yup, no 123 in $_n";
}
But that isn't going to match; at least, not the way you're hoping. It claims
that there is no 123 in the string. Here's a clearer picture of why it that
pattern matches, contrary to popular expectations:
$x = 'ABC123' ;
$y = 'ABC445' ;
print "1: got $1n" if $x =~ /^(ABC)(?!123)/ ;
print "2: got $1n" if $y =~ /^(ABC)(?!123)/ ;
print "3: got $1n" if $x =~ /^(D*)(?!123)/ ;
print "4: got $1n" if $y =~ /^(D*)(?!123)/ ;
This prints
2: got ABC
3: got AB
4: got ABC
You might have expected test 3 to fail because it seems to a more general
purpose version of test 1. The important difference between them is that test 3
contains a quantifier (D*) and so can use backtracking, whereas
test 1 will not. What's happening is that you've asked ``Is it true that at the
start of $x, following 0 or more non-digits, you have something that's not
123?'' If the pattern matcher had let D* expand to ``ABC'', this would have caused the whole pattern to fail. The
search engine will initially match D* with ``ABC''. Then it will try to match (?!123 with
``123'', which of course fails. But because a quantifier (D*) has
been used in the regular expression, the search engine can backtrack and retry
the match differently in the hope of matching the complete regular expression.
The pattern really, really wants to succeed, so it uses the standard
pattern back-off-and-retry and lets D* expand to just ``AB'' this time. Now there's indeed something following ``AB'' that is not ``123''. It's in fact ``C123'', which suffices.
We can deal with this by using both an assertion and a negation. We'll say
that the first part in $1 must be followed by a digit, and in fact,
it must also be followed by something that's not ``123''. Remember that the
lookaheads are zero-width expressions--they only look, but don't consume any of
the string in their match. So rewriting this way produces what you'd expect;
that is, case 5 will fail, but case 6 succeeds:
print "5: got $1n" if $x =~ /^(D*)(?=d)(?!123)/ ;
print "6: got $1n" if $y =~ /^(D*)(?=d)(?!123)/ ;
6: got ABC
In other words, the two zero-width assertions next to each other work as
though they're ANDed together, just as you'd use any builtin assertions:
/^$/ matches only if you're at the beginning of the line AND the end of the line simultaneously. The deeper underlying
truth is that juxtaposition in regular expressions always means AND, except when you write an explicit OR
using the vertical bar. /ab/ means match ``a'' AND (then) match ``b'', although the attempted matches are made
at different positions because ``a'' is not a zero-width assertion, but a
one-width assertion.
One warning: particularly complicated regular expressions can take
exponential time to solve due to the immense number of possible ways they can
use backtracking to try match. For example this will take a very long time to
run
/((a{0,5}){0,5}){0,5}/
And if you used *'s instead of limiting it to 0 through 5
matches, then it would take literally forever--or until you ran out of stack
space.
A powerful tool for optimizing such beasts is
``independent'' groups, which do not backtrace (see
(?>pattern)). Note also that zero-length
lookahead/lookbehind assertions will not backtrace to make the tail match, since
they are in ``logical'' context: only the fact whether they match or not is
considered relevant. For an example where side-effects of a lookahead
might have influenced the following match, see
(?>pattern).
Version 8 Regular Expressions
In case you're not familiar with the ``regular'' Version 8 regex routines,
here are the pattern-matching rules not described above.
Any single character matches itself, unless it is a metacharacter
with a special meaning described here or above. You can cause characters that
normally function as metacharacters to be interpreted literally by prefixing
them with a ``'' (e.g., ``.'' matches a ``.'', not any character; ``\''
matches a ``''). A series of characters matches that
series of characters in the target string, so the pattern blurfl
would match ``blurfl'' in the target string.
You can specify a character class, by enclosing a list of characters in
[], which will match any one character from the list. If the first
character after the ``['' is ``^'', the class matches any character not in the
list. Within a list, the ``-'' character is used to specify a range, so that
a-z represents all characters between ``a'' and ``z'', inclusive.
If you want ``-'' itself to be a member of a class, put it at the start or end
of the list, or escape it with a backslash. (The following all specify the same
class of three characters: [-az], [az-], and
[a-z]. All are different from [a-z], which specifies
a class containing twenty-six characters.)
Characters may be specified using a metacharacter syntax much like that used
in C: ``n'' matches a newline, ``t'' a tab, ``r'' a
carriage return, ``f'' a form feed, etc. More generally, nnn, where
nnn is a string of octal digits, matches the character whose ASCII value is nnn. Similarly, xnn, where
nn are hexadecimal digits, matches the character whose ASCII value is nn. The expression cx matches
the ASCII character control-x. Finally, the ``.''
metacharacter matches any character except ``n'' (unless you use /s).
You can specify a series of alternatives for a pattern using ``|'' to
separate them, so that fee|fie|foe will match any of ``fee'',
``fie'', or ``foe'' in the target string (as would f(e|i|o)e). The
first alternative includes everything from the last pattern delimiter (``('',
``['', or the beginning of the pattern) up to the first ``|'', and the last
alternative contains everything from the last ``|'' to the next pattern
delimiter. For this reason, it's common practice to include alternatives in
parentheses, to minimize confusion about where they start and end.
Alternatives are tried from left to right, so the first alternative found for
which the entire expression matches, is the one that is chosen. This means that
alternatives are not necessarily greedy. For example: when mathing
foo|foot against ``barefoot'', only the ``foo'' part will match, as
that is the first alternative tried, and it successfully matches the target
string. (This might not seem important, but it is important when you are
capturing matched text using parentheses.)
Also remember that ``|'' is interpreted as a literal within square brackets,
so if you write [fee|fie|foe] you're really only matching
[feio|].
Within a pattern, you may designate subpatterns for later reference by
enclosing them in parentheses, and you may refer back to the nth
subpattern later in the pattern using the metacharacter n. Subpatterns
are numbered based on the left to right order of their opening parenthesis.
A backreference matches whatever actually matched the
subpattern in the string being examined, not the rules for that subpattern.
Therefore, (0|0x)d*s1d* will match ``0x1234 0x4321'', but not
``0x1234 01234'', because subpattern 1 actually matched ``0x'', even though the
rule 0|0x could potentially match the leading 0 in the second
number.
WARNING on 1 vs $1
Some people get too used to writing things like:
$pattern =~ s/(W)/\1/g;
This is grandfathered for the RHS of a substitute to
avoid shocking the sed addicts, but it's a dirty habit to get
into. That's because in PerlThink, the righthand side of a s///
is a double-quoted string. 1 in the usual double-quoted string
means a control-A. The customary Unix meaning of 1 is kludged in
for s///.
However, if you get into the habit of doing that, you get yourself into trouble
if you then add an /e modifier.
s/(d+)/ 1 + 1 /eg; # causes warning under -w
Or if you try to do
s/(d+)/1000/;
You can't disambiguate that by saying {1}000, whereas you can
fix it with ${1}000. Basically, the operation of interpolation
should not be confused with the operation of matching a backreference. Certainly
they mean two different things on the left side of the s///.
Repeated patterns matching
zero-length substring
WARNING: Difficult material (and prose) ahead. This
section needs a rewrite.
Regular expressions provide a terse and powerful programming language. As
with most other power tools, power comes together with the ability to wreak
havoc.
A common abuse of this power stems from the ability to
make infinite loops using regular expressions, with something as innocous as:
'foo' =~ m{ ( o? )* }x;
The o? can match at the beginning of 'foo', and
since the position in the string is not moved by the match, o?
would match again and again due to the * modifier. Another common
way to create a similar cycle is with the looping modifier //g:
@matches = ( 'foo' =~ m{ o? }xg );
or
print "match: <$&>n" while 'foo' =~ m{ o? }xg;
or the loop implied by split().
However, long experience has shown that many programming tasks may be
significantly simplified by using repeated subexpressions which may match
zero-length substrings, with a simple example being:
@chars = split //, $string; # // is not magic in split
($whitewashed = $string) =~ s/()/ /g; # parens avoid magic s// /
Thus Perl allows the /()/ construct, which forcefully breaks
the infinite loop. The rules for this are different for lower-level loops
given by the greedy modifiers *+{}, and for higher-level ones like
the /g modifier or split() operator.
The lower-level loops are interrupted when it is detected that a
repeated expression did match a zero-length substring, thus
m{ (?: NON_ZERO_LENGTH | ZERO_LENGTH )* }x;
is made equivalent to
m{ (?: NON_ZERO_LENGTH )*
|
(?: ZERO_LENGTH )?
}x;
The higher level-loops preserve an additional state between iterations:
whether the last match was zero-length. To break the loop, the following match
after a zero-length match is prohibited to have a length of zero. This
prohibition interacts with backtracking (see Backtracking),
and so the second best match is chosen if the best match is of
zero length.
Say,
$_ = 'bar';
s/w??/<$&>/g;
results in
"<<b><><a><><r><>``>. At
each position of the string the best match given by non-greedy ??
is the zero-length match, and the second best match is what is matched
by w. Thus zero-length matches alternate with one-character-long
matches.
Similarly, for repeated m/()/g the second-best match is the
match at the position one notch further in the string.
The additional state of being matched with zero-length is associated
to the matched string, and is reset by each assignment to pos().
Creating custom RE engines
Overloaded constants (see the overload
manpage) provide a simple way to extend the functionality of the RE engine.
Suppose that we want to enable a new RE escape-sequence
Y| which matches at boundary between white-space characters and
non-whitespace characters. Note that
(?=S)(?<!S)|(?!S)(?<=S) matches exactly at these
positions, so we want to have each Y| in the place of the more
complicated version. We can create a module customre to do this:
package customre;
use overload;
sub import {
shift;
die "No argument to customre::import allowed" if @_;
overload::constant 'qr' => &convert;
}
sub invalid { die "/$_[0]/: invalid escape '\$_[1]'"}
my %rules = ( '\' => '\',
'Y|' => qr/(?=S)(?<!S)|(?!S)(?<=S)/ );
sub convert {
my $re = shift;
$re =~ s{
\ ( \ | Y . )
}
{ $rules{$1} or invalid($re,$1) }sgex;
return $re;
}
Now use customre enables the new escape in constant regular
expressions, i.e., those without any runtime variable interpolations. As
documented in the overload
manpage, this conversion will work only over literal parts of regular
expressions. For Y|$reY| the variable part of this regular
expression needs to be converted explicitly (but only if the special meaning of
Y| should be enabled inside $re):
use customre;
$re = <>;
chomp $re;
$re = customre::convert $re;
/Y|$reY|/;
SEE ALSO
Regexp
Quote-Like Operators.
Gory
details of parsing quoted constructs.
pos.
the
perllocale manpage.
Mastering Regular Expressions (see the perlbook
manpage) by Jeffrey Friedl.
Compilation Copyright © 1998-2000 O'Reilly & Associates, Inc.