我正在寻找解释以下语法的帮助。我已经检查了我的Perl书,并在网上检查了一下。
我正在寻找以下内容:
$option =~ s/s+//g
$option =~ m/^s*$
非常感谢。
s
和m
是将正则表达式应用于字符串的运算符。 s///
是替换运算符,m//
是匹配运算符。它们都采用正则表达式作为第一个参数(在//
内)。=~
告诉Perl使用/匹配正则表达式与$option
。有关此内容的更多信息,请参阅perlre
。
以下是这些正则表达式的作用:
use warnings;
use strict;
use YAPE::Regex::Explain;
print YAPE::Regex::Explain->new( qr/s+/ )->explain;
The regular expression:
(?-imsx:s+)
matches as follows:
NODE EXPLANATION
----------------------------------------------------------------------
(?-imsx: group, but do not capture (case-sensitive)
(with ^ and $ matching normally) (with . not
matching n) (matching whitespace and #
normally):
----------------------------------------------------------------------
s+ whitespace (n, r, t, f, and " ") (1 or
more times (matching the most amount
possible))
----------------------------------------------------------------------
) end of grouping
----------------------------------------------------------------------
简而言之:它替换了每个包含多个空格字符的实例
,而没有任何内容。和:
print YAPE::Regex::Explain->new( qr/^s*$/ )->explain;
正则表达式:
(?-imsx:^s*$)
matches as follows:
NODE EXPLANATION
----------------------------------------------------------------------
(?-imsx: group, but do not capture (case-sensitive)
(with ^ and $ matching normally) (with . not
matching n) (matching whitespace and #
normally):
----------------------------------------------------------------------
^ the beginning of the string
----------------------------------------------------------------------
s* whitespace (n, r, t, f, and " ") (0 or
more times (matching the most amount
possible))
----------------------------------------------------------------------
$ before an optional n, and the end of the
string
----------------------------------------------------------------------
) end of grouping
----------------------------------------------------------------------
如果字符串仅包含空格字符,则该字符串匹配。尽可能多的,但至少为零,仅此而已。
嗯,第一个表达式是一个s
(ubstitution),它查找一个或多个空格并消除它们。 +
指定一个或多个空格(s
)字符。
第二个看起来m
(atch)一个空行。 ^
将匹配项锚定到行的开头,将$
锚定到行尾。 因此,只有包含零或多(即 *
) 空格匹配成功。
这两个表达式都对 $option
变量进行操作,因为=~
将它们绑定到该变量。