perlretut.html
来自「perl教程」· HTML 代码 · 共 919 行 · 第 1/5 页
HTML
919 行
</pre>
<p>If the groupings in a regexp are nested, <code>$1</code> gets the group with the
leftmost opening parenthesis, <code>$2</code> the next opening parenthesis,
etc. For example, here is a complex regexp and the matching variables
indicated below it:</p>
<pre>
<span class="regex">/(ab(cd|ef)((gi)|j))/</span><span class="operator">;</span>
<span class="number">1</span> <span class="number">2</span> <span class="number">34</span>
</pre>
<p>so that if the regexp matched, e.g., <code>$2</code> would contain 'cd' or 'ef'. For
convenience, perl sets <a href="../../lib/Pod/perlvar.html#item___"><code>$+</code></a> to the string held by the highest numbered
<code>$1</code>, <code>$2</code>, ... that got assigned (and, somewhat related, <a href="../../lib/Pod/perlvar.html#item___n"><code>$^N</code></a> to the
value of the <code>$1</code>, <code>$2</code>, ... most-recently assigned; i.e. the <code>$1</code>,
<code>$2</code>, ... associated with the rightmost closing parenthesis used in the
match).</p>
<p>Closely associated with the matching variables <code>$1</code>, <code>$2</code>, ... are
the <strong>backreferences</strong> <code>\1</code>, <code>\2</code>, ... . Backreferences are simply
matching variables that can be used <em>inside</em> a regexp. This is a
really nice feature - what matches later in a regexp can depend on
what matched earlier in the regexp. Suppose we wanted to look
for doubled words in text, like 'the the'. The following regexp finds
all 3-letter doubles with a space in between:</p>
<pre>
<span class="regex">/(\w\w\w)\s\1/</span><span class="operator">;</span>
</pre>
<p>The grouping assigns a value to \1, so that the same 3 letter sequence
is used for both parts. Here are some words with repeated parts:</p>
<pre>
% simple_grep '^(\w\w\w\w|\w\w\w|\w\w|\w)\1$' /usr/dict/words
beriberi
booboo
coco
mama
murmur
papa</pre>
<p>The regexp has a single grouping which considers 4-letter
combinations, then 3-letter combinations, etc. and uses <code>\1</code> to look for
a repeat. Although <code>$1</code> and <code>\1</code> represent the same thing, care should be
taken to use matched variables <code>$1</code>, <code>$2</code>, ... only outside a regexp
and backreferences <code>\1</code>, <code>\2</code>, ... only inside a regexp; not doing
so may lead to surprising and/or undefined results.</p>
<p>In addition to what was matched, Perl 5.6.0 also provides the
positions of what was matched with the <a href="../../lib/Pod/perlvar.html#item__"><code>@-</code></a> and <a href="../../lib/Pod/perlvar.html#item___"><code>@+</code></a>
arrays. <code>$-[0]</code> is the position of the start of the entire match and
<code>$+[0]</code> is the position of the end. Similarly, <code>$-[n]</code> is the
position of the start of the <code>$n</code> match and <code>$+[n]</code> is the position
of the end. If <code>$n</code> is undefined, so are <code>$-[n]</code> and <code>$+[n]</code>. Then
this code</p>
<pre>
<span class="variable">$x</span> <span class="operator">=</span> <span class="string">"Mmm...donut, thought Homer"</span><span class="operator">;</span>
<span class="variable">$x</span> <span class="operator">=~</span> <span class="regex">/^(Mmm|Yech)\.\.\.(donut|peas)/</span><span class="operator">;</span> <span class="comment"># matches</span>
<span class="keyword">foreach</span> <span class="variable">$expr</span> <span class="operator">(</span><span class="number">1</span><span class="operator">..</span><span class="variable">$#-</span><span class="operator">)</span> <span class="operator">{</span>
<span class="keyword">print</span> <span class="string">"Match $expr: '${$expr}' at position ($-[$expr],$+[$expr])\n"</span><span class="operator">;</span>
<span class="operator">}</span>
</pre>
<p>prints</p>
<pre>
Match 1: 'Mmm' at position (0,3)
Match 2: 'donut' at position (6,11)</pre>
<p>Even if there are no groupings in a regexp, it is still possible to
find out what exactly matched in a string. If you use them, perl
will set <a href="../../lib/Pod/perlvar.html#item___"><code>$`</code></a> to the part of the string before the match, will set <a href="../../lib/Pod/perlvar.html#item___"><code>$&</code></a>
to the part of the string that matched, and will set <a href="../../lib/Pod/perlvar.html#item___"><code>$'</code></a> to the part
of the string after the match. An example:</p>
<pre>
<span class="variable">$x</span> <span class="operator">=</span> <span class="string">"the cat caught the mouse"</span><span class="operator">;</span>
<span class="variable">$x</span> <span class="operator">=~</span> <span class="regex">/cat/</span><span class="operator">;</span> <span class="comment"># $` = 'the ', $& = 'cat', $' = ' caught the mouse'</span>
<span class="variable">$x</span> <span class="operator">=~</span> <span class="regex">/the/</span><span class="operator">;</span> <span class="comment"># $` = '', $& = 'the', $' = ' cat caught the mouse'</span>
</pre>
<p>In the second match, <a href="../../lib/Pod/perlvar.html#item___"><code>$` = ''</code></a> because the regexp matched at the
first character position in the string and stopped, it never saw the
second 'the'. It is important to note that using <a href="../../lib/Pod/perlvar.html#item___"><code>$`</code></a> and <a href="../../lib/Pod/perlvar.html#item___"><code>$'</code></a>
slows down regexp matching quite a bit, and <code> $& </code> slows it down to a
lesser extent, because if they are used in one regexp in a program,
they are generated for <all> regexps in the program. So if raw
performance is a goal of your application, they should be avoided.
If you need them, use <a href="../../lib/Pod/perlvar.html#item__"><code>@-</code></a> and <a href="../../lib/Pod/perlvar.html#item___"><code>@+</code></a> instead:</p>
<pre>
$` is the same as substr( $x, 0, $-[0] )
$& is the same as substr( $x, $-[0], $+[0]-$-[0] )
$' is the same as substr( $x, $+[0] )</pre>
<p>
</p>
<h2><a name="matching_repetitions">Matching repetitions</a></h2>
<p>The examples in the previous section display an annoying weakness. We
were only matching 3-letter words, or syllables of 4 letters or
less. We'd like to be able to match words or syllables of any length,
without writing out tedious alternatives like
<code>\w\w\w\w|\w\w\w|\w\w|\w</code>.</p>
<p>This is exactly the problem the <strong>quantifier</strong> metacharacters <code>?</code>,
<code>*</code>, <code>+</code>, and <code>{}</code> were created for. They allow us to determine the
number of repeats of a portion of a regexp 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:</p>
<ul>
<li>
<p><code>a?</code> = match 'a' 1 or 0 times</p>
</li>
<li>
<p><code>a*</code> = match 'a' 0 or more times, i.e., any number of times</p>
</li>
<li>
<p><code>a+</code> = match 'a' 1 or more times, i.e., at least once</p>
</li>
<li>
<p><code>a{n,m}</code> = match at least <a href="../../lib/Pod/perlguts.html#item_n"><code>n</code></a> times, but not more than <a href="../../lib/Pod/perlguts.html#item_m"><code>m</code></a>
times.</p>
</li>
<li>
<p><code>a{n,}</code> = match at least <a href="../../lib/Pod/perlguts.html#item_n"><code>n</code></a> or more times</p>
</li>
<li>
<p><code>a{n}</code> = match exactly <a href="../../lib/Pod/perlguts.html#item_n"><code>n</code></a> times</p>
</li>
</ul>
<p>Here are some examples:</p>
<pre>
<span class="regex">/[a-z]+\s+\d*/</span><span class="operator">;</span> <span class="comment"># match a lowercase word, at least some space, and</span>
<span class="comment"># any number of digits</span>
<span class="regex">/(\w+)\s+\1/</span><span class="operator">;</span> <span class="comment"># match doubled words of arbitrary length</span>
<span class="regex">/y(es)?/i</span><span class="operator">;</span> <span class="comment"># matches 'y', 'Y', or a case-insensitive 'yes'</span>
<span class="variable">$year</span> <span class="operator">=~</span> <span class="regex">/\d{2,4}/</span><span class="operator">;</span> <span class="comment"># make sure year is at least 2 but not more</span>
<span class="comment"># than 4 digits</span>
<span class="variable">$year</span> <span class="operator">=~</span> <span class="regex">/\d{4}|\d{2}/</span><span class="operator">;</span> <span class="comment"># better match; throw out 3 digit dates</span>
<span class="variable">$year</span> <span class="operator">=~</span> <span class="regex">/\d{2}(\d{2})?/</span><span class="operator">;</span> <span class="comment"># same thing written differently. However,</span>
<span class="comment"># this produces $1 and the other does not.</span>
</pre>
<pre>
% simple_grep '^(\w+)\1$' /usr/dict/words # isn't this easier?
beriberi
booboo
coco
mama
murmur
papa</pre>
<p>For all of these quantifiers, perl will try to match as much of the
string as possible, while still allowing the regexp to succeed. Thus
with <code>/a?.../</code>, perl will first try to match the regexp with the <code>a</code>
present; if that fails, perl will try to match the regexp without the
<code>a</code> present. For the quantifier <code>*</code>, we get the following:</p>
<pre>
<span class="variable">$x</span> <span class="operator">=</span> <span class="string">"the cat in the hat"</span><span class="operator">;</span>
<span class="variable">$x</span> <span class="operator">=~</span> <span class="regex">/^(.*)(cat)(.*)$/</span><span class="operator">;</span> <span class="comment"># matches,</span>
<span class="comment"># $1 = 'the '</span>
<span class="comment"># $2 = 'cat'</span>
<span class="comment"># $3 = ' in the hat'</span>
</pre>
<p>Which is what we might expect, the match finds the only <code>cat</code> in the
string and locks onto it. Consider, however, this regexp:</p>
<pre>
<span class="variable">$x</span> <span class="operator">=~</span> <span class="regex">/^(.*)(at)(.*)$/</span><span class="operator">;</span> <span class="comment"># matches,</span>
<span class="comment"># $1 = 'the cat in the h'</span>
<span class="comment"># $2 = 'at'</span>
<span class="comment"># $3 = '' (0 matches)</span>
</pre>
<p>One might initially guess that perl would find the <code>at</code> in <code>cat</code> and
stop there, but that wouldn't give the longest possible string to the
first quantifier <code>.*</code>. Instead, the first quantifier <code>.*</code> grabs as
much of the string as possible while still having the regexp match. In
this example, that means having the <code>at</code> sequence with the final <code>at</code>
in the string. The other important principle illustrated here is that
when there are two or more elements in a regexp, the <em>leftmost</em>
quantifier, if there is one, gets to grab as much the string as
possible, leaving the rest of the regexp to fight over scraps. Thus in
our example, the first quantifier <code>.*</code> grabs most of the string, while
the second quantifier <code>.*</code> gets the empty string. Quantifiers that
grab as much of the string as possible are called <strong>maximal match</strong> or
<strong>greedy</strong> quantifiers.</p>
<p>When a regexp can match a string in several different ways, we can use
the principles above to predict which way the regexp will match:</p>
<ul>
<li>
<p>Principle 0: Taken as a whole, any regexp will be matched at the
earliest possible position in the string.</p>
</li>
<li>
<p>Principle 1: In an alternation <code>a|b|c...</code>, the leftmost alternative
that allows a match for the whole regexp will be the one used.</p>
</li>
<li>
<p>Principle 2: The maximal matching quantifiers <code>?</code>, <code>*</code>, <code>+</code> and
<co
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?