免费注册 查看新帖 |

Chinaunix

广告
  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 6324 | 回复: 4
打印 上一主题 下一主题

perl 正则表达式中的字符串变量含有中括号 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2012-07-12 11:05 |只看该作者 |倒序浏览
请教一下各位,百思不得其解。
perl 正则表达式中的字符串变量含有中括号,结果就无法匹配成功。
$a="abc[0]";
$b="bc[0]";
$a=~/$b/;
这样的匹配怎么也不成功,如果b没有中括号就可以,请问b中带有中括号,我该怎么匹配呢。谢谢哥哥帮助。

论坛徽章:
0
2 [报告]
发表于 2012-07-12 11:10 |只看该作者
$a=~/\Q$b\E/;

论坛徽章:
0
3 [报告]
发表于 2012-07-12 12:07 |只看该作者
或者用quotemeta

论坛徽章:
0
4 [报告]
发表于 2012-07-12 16:17 |只看该作者
In Perl regular expressions, you can surround a subexpression with \Q and \E to indicate that you want that subexpression to be matched as a literal string even if there are metacharacters in there. You also have the quotemeta function that inserts exactly the right number of backslashes in a string so that if you subsequently interpolate that string into a regular expression, it will be matched literally, no matter what its contents were!
  1. #!/usr/bin/perl -w
  2. use strict;
  3. use warnings;


  4. my $a="abc[0]";
  5. my $b="bc[0]";
  6. my $c=quotemeta($b); # $c eq ‘bc\[0\]’;
  7. if($a=~/$c/){print "match\n";} # results in “match” being printed.
  8. if($a=~/\Q$b\E/){print "match\n";} # results in “match” being printed.

复制代码

论坛徽章:
0
5 [报告]
发表于 2012-11-05 17:20 |只看该作者
4楼的太好太详细了 mark之
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP