perl-正则变量捕捉

1、使用默认数字捕捉

use 5.010;

my $names='deep and future';

iif ($names=~m/(\w+)  (and|or)  (\w+)/){

    say "I saw $1 and $3";#为什么不是$2,因为一个括号代表可捕捉位置,$2是and|or

}

输出 I saw deep and future

2、使用变量名捕捉

use 5.010;

my $names='deep and future';

iif ($names=~m/((?<pname1>\w+)  (and|or)  (?<pname2>\w+)/){

    say "I saw $+{pname1} and $+{pname2}";

}

3、指定不捕捉某些括号,使用(?:)

use 5.010;

my $names='deep and future';

iif ($names=~m/(\w+)  (?:and|or)  (\w+)/){

    say "I saw $1 and $2";#and|or不捕捉

}

4、使用自动变量匹配

$`表示匹配起始位置之前的字符串

$&表示匹配的内容,即//内的内容

$'表示匹配终结位置之后的内容

use 5.010;

my $names='hello! deep and future';
if ($names=~m/o!\s(\w+)/){
say $`;
say $&;
say $';
say $1;
}

 

输出:

 hell
o! deep
 and future
deep

你可能感兴趣的:(perl)