perl模式匹配中用含特殊字符的变量?(using a variable as a patt
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 chomp( my $regex = <STDIN> ); if( $string =~ m/$regex/ ) { ... } Any regular expression special characters in 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 chomp( my $regex = <STDIN> ); if( $string =~ m/$regex/ ) { ... } You can also do this directly in the match operator using the chomp( my $regex = <STDIN> ); if( $string =~ m/ $regex /) { ... } Alternately,you can use 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 chomp( my $input = <STDIN> ); eval { Or... my $regex = eval { qr/$input/is }; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |