2

我目前正在研究一个函数,它接受一个关键字列表和一个字符串(一个 looong 字符串)作为参数,我希望它返回每个匹配关键字的列表。问题是关键字可以是 2 个单词。例如 - keyword1 : foobar, keyword2 : foo bar, keyword3 : barfoo)

细绳:

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 ;

这适用于简单的单词,但不适用于组合单词:/

任何想法 ?

谢谢您的帮助。

4

2 回答 2

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);
于 2013-09-26T12:21:02.890 回答
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)

顺便说一句,如果您删除它返回的修饰符(foobar,foo bar),您的代码@matches = $string =~ m/\b(?:foobar|foo bar)\b/gi;也很好用/i

于 2013-09-26T12:19:02.713 回答