perlretut.html
来自「perl教程」· HTML 代码 · 共 919 行 · 第 1/5 页
HTML
919 行
<span class="variable">$x</span> <span class="operator">=~</span> <span class="regex">/\AWho/m</span><span class="operator">;</span> <span class="comment"># doesn't match, "Who" is not at start of string</span>
</pre>
<pre>
<span class="variable">$x</span> <span class="operator">=~</span> <span class="regex">/girl$/m</span><span class="operator">;</span> <span class="comment"># matches, "girl" at end of first line</span>
<span class="variable">$x</span> <span class="operator">=~</span> <span class="regex">/girl\Z/m</span><span class="operator">;</span> <span class="comment"># doesn't match, "girl" is not at end of string</span>
</pre>
<pre>
<span class="variable">$x</span> <span class="operator">=~</span> <span class="regex">/Perl\Z/m</span><span class="operator">;</span> <span class="comment"># matches, "Perl" is at newline before end</span>
<span class="variable">$x</span> <span class="operator">=~</span> <span class="regex">/Perl\z/m</span><span class="operator">;</span> <span class="comment"># doesn't match, "Perl" is not at end of string</span>
</pre>
<p>We now know how to create choices among classes of characters in a
regexp. What about choices among words or character strings? Such
choices are described in the next section.</p>
<p>
</p>
<h2><a name="matching_this_or_that">Matching this or that</a></h2>
<p>Sometimes we would like our regexp to be able to match different
possible words or character strings. This is accomplished by using
the <strong>alternation</strong> metacharacter <code>|</code>. To match <code>dog</code> or <code>cat</code>, we
form the regexp <code>dog|cat</code>. As before, perl will try to match the
regexp at the earliest possible point in the string. At each
character position, perl will first try to match the first
alternative, <code>dog</code>. If <code>dog</code> doesn't match, perl will then try the
next alternative, <code>cat</code>. If <code>cat</code> doesn't match either, then the
match fails and perl moves to the next position in the string. Some
examples:</p>
<pre>
<span class="string">"cats and dogs"</span> <span class="operator">=~</span> <span class="regex">/cat|dog|bird/</span><span class="operator">;</span> <span class="comment"># matches "cat"</span>
<span class="string">"cats and dogs"</span> <span class="operator">=~</span> <span class="regex">/dog|cat|bird/</span><span class="operator">;</span> <span class="comment"># matches "cat"</span>
</pre>
<p>Even though <code>dog</code> is the first alternative in the second regexp,
<code>cat</code> is able to match earlier in the string.</p>
<pre>
<span class="string">"cats"</span> <span class="operator">=~</span> <span class="regex">/c|ca|cat|cats/</span><span class="operator">;</span> <span class="comment"># matches "c"</span>
<span class="string">"cats"</span> <span class="operator">=~</span> <span class="regex">/cats|cat|ca|c/</span><span class="operator">;</span> <span class="comment"># matches "cats"</span>
</pre>
<p>Here, all the alternatives match at the first string position, so the
first alternative is the one that matches. If some of the
alternatives are truncations of the others, put the longest ones first
to give them a chance to match.</p>
<pre>
"cab" =~ /a|b|c/ # matches "c"
# /a|b|c/ == /[abc]/</pre>
<p>The last example points out that character classes are like
alternations of characters. At a given character position, the first
alternative that allows the regexp match to succeed will be the one
that matches.</p>
<p>
</p>
<h2><a name="grouping_things_and_hierarchical_matching">Grouping things and hierarchical matching</a></h2>
<p>Alternation allows a regexp to choose among alternatives, but by
itself it unsatisfying. The reason is that each alternative is a whole
regexp, but sometime we want alternatives for just part of a
regexp. For instance, suppose we want to search for housecats or
housekeepers. The regexp <code>housecat|housekeeper</code> fits the bill, but is
inefficient because we had to type <code>house</code> twice. It would be nice to
have parts of the regexp be constant, like <code>house</code>, and some
parts have alternatives, like <code>cat|keeper</code>.</p>
<p>The <strong>grouping</strong> metacharacters <code>()</code> solve this problem. Grouping
allows parts of a regexp to be treated as a single unit. Parts of a
regexp are grouped by enclosing them in parentheses. Thus we could solve
the <code>housecat|housekeeper</code> by forming the regexp as
<code>house(cat|keeper)</code>. The regexp <code>house(cat|keeper)</code> means match
<code>house</code> followed by either <code>cat</code> or <code>keeper</code>. Some more examples
are</p>
<pre>
<span class="regex">/(a|b)b/</span><span class="operator">;</span> <span class="comment"># matches 'ab' or 'bb'</span>
<span class="regex">/(ac|b)b/</span><span class="operator">;</span> <span class="comment"># matches 'acb' or 'bb'</span>
<span class="regex">/(^a|b)c/</span><span class="operator">;</span> <span class="comment"># matches 'ac' at start of string or 'bc' anywhere</span>
<span class="regex">/(a|[bc])d/</span><span class="operator">;</span> <span class="comment"># matches 'ad', 'bd', or 'cd'</span>
</pre>
<pre>
<span class="regex">/house(cat|)/</span><span class="operator">;</span> <span class="comment"># matches either 'housecat' or 'house'</span>
<span class="regex">/house(cat(s|)|)/</span><span class="operator">;</span> <span class="comment"># matches either 'housecats' or 'housecat' or</span>
<span class="comment"># 'house'. Note groups can be nested.</span>
</pre>
<pre>
<span class="regex">/(19|20|)\d\d/</span><span class="operator">;</span> <span class="comment"># match years 19xx, 20xx, or the Y2K problem, xx</span>
<span class="string">"20"</span> <span class="operator">=~</span> <span class="regex">/(19|20|)\d\d/</span><span class="operator">;</span> <span class="comment"># matches the null alternative '()\d\d',</span>
<span class="comment"># because '20\d\d' can't match</span>
</pre>
<p>Alternations behave the same way in groups as out of them: at a given
string position, the leftmost alternative that allows the regexp to
match is taken. So in the last example at the first string position,
<code>"20"</code> matches the second alternative, but there is nothing left over
to match the next two digits <code>\d\d</code>. So perl moves on to the next
alternative, which is the null alternative and that works, since
<code>"20"</code> is two digits.</p>
<p>The process of trying one alternative, seeing if it matches, and
moving on to the next alternative if it doesn't, is called
<strong>backtracking</strong>. The term 'backtracking' comes from the idea that
matching a regexp is like a walk in the woods. Successfully matching
a regexp is like arriving at a destination. There are many possible
trailheads, one for each string position, and each one is tried in
order, left to right. From each trailhead there may be many paths,
some of which get you there, and some which are dead ends. When you
walk along a trail and hit a dead end, you have to backtrack along the
trail to an earlier point to try another trail. If you hit your
destination, you stop immediately and forget about trying all the
other trails. You are persistent, and only if you have tried all the
trails from all the trailheads and not arrived at your destination, do
you declare failure. To be concrete, here is a step-by-step analysis
of what perl does when it tries to match the regexp</p>
<pre>
<span class="string">"abcde"</span> <span class="operator">=~</span> <span class="regex">/(abd|abc)(df|d|de)/</span><span class="operator">;</span>
</pre>
<ol>
<li>
<p>Start with the first letter in the string 'a'.</p>
</li>
<li>
<p>Try the first alternative in the first group 'abd'.</p>
</li>
<li>
<p>Match 'a' followed by 'b'. So far so good.</p>
</li>
<li>
<p>'d' in the regexp doesn't match 'c' in the string - a dead
end. So backtrack two characters and pick the second alternative in
the first group 'abc'.</p>
</li>
<li>
<p>Match 'a' followed by 'b' followed by 'c'. We are on a roll
and have satisfied the first group. Set $1 to 'abc'.</p>
</li>
<li>
<p>Move on to the second group and pick the first alternative
'df'.</p>
</li>
<li>
<p>Match the 'd'.</p>
</li>
<li>
<p>'f' in the regexp doesn't match 'e' in the string, so a dead
end. Backtrack one character and pick the second alternative in the
second group 'd'.</p>
</li>
<li>
<p>'d' matches. The second grouping is satisfied, so set $2 to
'd'.</p>
</li>
<li>
<p>We are at the end of the regexp, so we are done! We have
matched 'abcd' out of the string "abcde".</p>
</li>
</ol>
<p>There are a couple of things to note about this analysis. First, the
third alternative in the second group 'de' also allows a match, but we
stopped before we got to it - at a given character position, leftmost
wins. Second, we were able to get a match at the first character
position of the string 'a'. If there were no matches at the first
position, perl would move to the second character position 'b' and
attempt the match all over again. Only when all possible paths at all
possible character positions have been exhausted does perl give
up and declare <code>$string =~ /(abd|abc)(df|d|de)/;</code> to be false.</p>
<p>Even with all this work, regexp matching happens remarkably fast. To
speed things up, during compilation stage, perl compiles the regexp
into a compact sequence of opcodes that can often fit inside a
processor cache. When the code is executed, these opcodes can then run
at full throttle and search very quickly.</p>
<p>
</p>
<h2><a name="extracting_matches">Extracting matches</a></h2>
<p>The grouping metacharacters <code>()</code> also serve another completely
different function: they allow the extraction of the parts of a string
that matched. This is very useful to find out what matched and for
text processing in general. For each grouping, the part that matched
inside goes into the special variables <code>$1</code>, <code>$2</code>, etc. They can be
used just as ordinary variables:</p>
<pre>
<span class="comment"># extract hours, minutes, seconds</span>
<span class="keyword">if</span> <span class="operator">(</span><span class="variable">$time</span> <span class="operator">=~</span> <span class="regex">/(\d\d):(\d\d):(\d\d)/</span><span class="operator">)</span> <span class="operator">{</span> <span class="comment"># match hh:mm:ss format</span>
<span class="variable">$hours</span> <span class="operator">=</span> <span class="variable">$1</span><span class="operator">;</span>
<span class="variable">$minutes</span> <span class="operator">=</span> <span class="variable">$2</span><span class="operator">;</span>
<span class="variable">$seconds</span> <span class="operator">=</span> <span class="variable">$3</span><span class="operator">;</span>
<span class="operator">}</span>
</pre>
<p>Now, we know that in scalar context,
<code>$time =~ /(\d\d):(\d\d):(\d\d)/</code> returns a true or false
value. In list context, however, it returns the list of matched values
<code>($1,$2,$3)</code>. So we could write the code more compactly as</p>
<pre>
<span class="comment"># extract hours, minutes, seconds</span>
<span class="operator">(</span><span class="variable">$hours</span><span class="operator">,</span> <span class="variable">$minutes</span><span class="operator">,</span> <span class="variable">$second</span><span class="operator">)</span> <span class="operator">=</span> <span class="operator">(</span><span class="variable">$time</span> <span class="operator">=~</span> <span class="regex">/(\d\d):(\d\d):(\d\d)/</span><span class="operator">);</span>
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?