$' $& $` 这 3 个符号对应 3 个自动变量,所谓自动变量就是根据匹配情况而自动设置的变量。
$& 变量存储所有匹配的部分。
$' 变量存储了匹配字符串身后没有匹配的部分。
$` 变量存储了匹配字符串身前没有匹配的部分。
测试代码:
[Perl] 纯文本查看 复制代码 #!/usr/bin/perl
if ("Welcome to Groad.net it is good" =~ /(\w+)\.(\w+)/) {
print "$1 $2\n";
print "That actually matched '$&' \n";
print "Before match '$`' \n";
print "After match '$'' \n";
}
运行输出:# ./character.pl
Groad net
That actually matched 'Groad.net'
Before match 'Welcome to '
After match ' it is good' 注意,在匹配模式里,'.' 符号要用反斜线转义,不然会被解析为点号的元字符含义,如果这样 /(\w+)\.(\w+)/ 就会匹配到 "Welcome to" ,因为正则表达式的“贪功"特性使它一旦发现匹配它就会马上返回邀功领赏。
一个实用的模式测试程序:
[Perl] 纯文本查看 复制代码 #!/usr/bin/perl
while (<>) {
chomp;
if (/groad/) {
print "Matched: |<[ ubbcodeplace_1 ]>|\n";
} else {
print "No match: |$_|\n";
}
}
运行输出:在上面的测试程序中,<> 不断的读入输入,然后进行匹配比较,这样可以检测某些字符串是否匹配指定的模式。 |