如何在 Perl 中使用 grep 检查字符串中是否存在任何数组值以及匹配的数组值

  • 本文关键字:数组 任何 存在 是否 字符串 Perl grep perl
  • 更新时间 :
  • 英文 :


我需要检查@val中的任何数组值是否与字符串$str匹配。如果是这样,我需要获取那里匹配的数组值。

这是针对运行Perl的窗口

$str ="This is a testabc code ";
@val=("not","hope","test","beta");
#How to find whether any of the @val elements are present in $str and also which element is matching using grep .

我需要在找到"测试"时获取输出

这应该这样做:

my $str="This is a test code ";
#$str.="not";
my @val=("not","hope","test","beta");
my @m=grep $str=~/$_/, @val;
print "Matched: @m";
print "First match, if any: $m[0]";

您还应该考虑是否需要不区分大小写的匹配。"互联网"也应该与"互联网"相匹配吗?如果您只想匹配整个单词或部分单词。"智能"是否也应该与"智能手机"相匹配?将/$_/更改为/$_/i以匹配不区分大小写的单词,更改为/b$_b/i以仅匹配整个单词。

最新更新