加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

perl模式匹配中用含特殊字符的变量?(using a variable as a patt

发布时间:2020-12-16 00:40:17 所属栏目:大数据 来源:网络整理
导读:We don't have to hard-code patterns into the match operator (or anything else that works with regular expressions). We can put the pattern in a variable for later use. The match operator is a double quote context,so you can interpolate you

We don't have to hard-code patterns into the match operator (or anything else that works with regular expressions). We can put the pattern in a variable for later use.

The match operator is a double quote context,so you can interpolate your variable just like a double quoted string. In this case,you read the regular expression as user input and store it in $regex . Once you have the pattern in $regex,you use that variable in the match operator.

chomp( my $regex = <STDIN> );
if( $string =~ m/$regex/ ) { ... }

Any regular expression special characters in $regex are still special,and the pattern still has to be valid or Perl will complain. For instance,in this pattern there is an unpaired parenthesis.

my $regex = "Unmatched ( paren";
"Two parens to bind them all" =~ m/$regex/;

When Perl compiles the regular expression,it treats the parenthesis as the start of a memory match. When it doesn't find the closing parenthesis,it complains:

Unmatched ( in regex; marked by <-- HERE in m/Unmatched ( <-- HERE  paren/ at script line 3.

You can get around this in several ways depending on our situation. First,if you don't want any of the characters in the string to be special,you can escape them with quotemeta before you use the string.

chomp( my $regex = <STDIN> );
$regex = quotemeta( $regex );
if( $string =~ m/$regex/ ) { ... }

You can also do this directly in the match operator using the /Q and /E sequences. The /Q tells Perl where to start escaping special characters,and the /E tells it where to stop (see perlop for more details).

chomp( my $regex = <STDIN> );
if( $string =~ m//Q$regex/E/ ) { ... }

Alternately,you can use qr//,the regular expression quote operator (see perlop for more details). It quotes and perhaps compiles the pattern,and you can apply regular expression flags to the pattern.

chomp( my $input = <STDIN> );
my $regex = qr/$input/is;
$string =~ m/$regex/  # same as m/$input/is;

You might also want to trap any errors by wrapping an eval block around the whole thing.

chomp( my $input = <STDIN> );
eval {
if( $string =~ m//Q$input/E/ ) { ... }
};
warn $@ if $@;

Or...

my $regex = eval { qr/$input/is };
if( defined $regex ) {
$string =~ m/$regex/;
}
else {
warn $@;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读