我目前正在开发一个函数,它接受一个关键字列表和一个字符串(一个looong字符串)作为参数,我希望它返回每个匹配关键字的列表。问题是关键字可以是2个单词。
例如 - keyword1 : foobar
,keyword2 : foo bar
,keyword3 : barfoo
)
string:
hi this is foobar, have you seen my foo bar, he is very fooBar ?
我想要一个包含(foobar
,foo bar
);
我得到的那一刻:
@matches = $string =~ m/\b(?:foobar|foo bar)\b/gi ;
这适用于简单的单词,但不适用于组合单词:/
任何想法?
感谢您的帮助。
答案 0 :(得分:1)
sub myfunc {
my ($str, @kw) = @_;
my ($re) = map qr/\b ($_) \b/x, join "|", @kw;
return $str =~ /$re/gi;
}
my @kwords = ("foobar", "foo bar", "barfoo");
my @arr = myfunc("hi this is foobar, have you seen my foo bar, he is very fooBar ?", @kwords);
答案 1 :(得分:0)
这会返回正确的结果:
sub match {
my @keywords=@_;
my $s=pop @keywords;
return grep {$s=~/\b\Q$_\E\b/i} @keywords;
}
my @matches=match('foobar','foo bar','barfoo)','hi this is foobar, have you seen my foo bar, he is very fooBar?'); #this returns (foobar, foo bar)
BTW你的代码@matches = $string =~ m/\b(?:foobar|foo bar)\b/gi;
工作得很好,如果你删除它返回的/i
修饰符(foobar,foo bar)