默认情况下,点号 ('.') 无法匹配换行符。也许在很多情况下我们也无需去匹配换行符,但有些时候却也希望能够匹配一下换行符,解决办法是使用 /s 来增强 '.' 号的功能,使之可以匹配换行符。这样一来, . 就能 匹配任何字符了。
说到匹配任何字符,那么还提到另外一个符合字符集 [\d\D] 。如果我们想匹配任何数字的字符集,那么可以写成 [0-9] ,而 [0-9] 又可以简写成 [\d] 。假如不想匹配数字,那么我们既可以写成 [^0-9] 还可以写成 [^\d] ,而 [^\d] 这种形式又可以以 [\d] 的反义形式 [\D] 来表示。所以 [\d\D] 合起来就表示“任何数字或非数字” ,换句话就是说,它可以匹配任何字符,而这个任意字符自然也是包括换行符的。
考虑下面代码:
[Perl] 纯文本查看 复制代码 #!/usr/bin/perl
$_ = "The network revolution is known as the frourth revolution \nfollowing the agricultural revolution,the industrial revolution \nand the information revolution.\n";
#print "$_";
if (/revolution.*and/) {
print "Ok, it match.\n";
} else {
print "\".*\" can not match the \'\\n\' \n";
}
if (/revolution.*and/s) {
print "OK, it match.\n"
} else {
print "/S can do nothing\n";
}
if (/revolution[\d\D]+and/) {
print "OK, this match too.\n"
} else {
print "can do nothing\n";
}
运行输出:# ./smatch.pl
".*" can not match the '\n'
OK, it match.
OK, this match too. 由输出可见,/s 可以使 '.' 号匹配换行符。
‘+’ 元字符表示“匹配前面的字符一次或多次” 。
‘*’ 元字符用来匹配前面的内容零次或多次。
.* 有个戏称---"捡破烂模式”,因为它通吃所有的字符串。 |