【问题标题】:Matching simple keyword and keyword with spaces匹配简单关键字和带空格的关键字
【发布时间】:2013-09-26 12:10:11
【问题描述】:

我目前正在研究一个函数,它接受一个关键字列表和一个字符串(一个 looong 字符串)作为参数,我希望它返回每个匹配关键字的列表。问题是关键字可以是 2 个单词。 例如 - keyword1 : foobarkeyword2 : foo barkeyword3 : 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 ;

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

有什么想法吗?

感谢您的帮助。

【问题讨论】:

  • 组合词是什么意思?
  • 有一个空格,比如“foo bar”,我希望它是一个关键字。我的意思是我必须以最快的方式来做,这意味着只滚动一次字符串。
  • 你能给我一个你不想匹配的例子吗?
  • 是的,你可以有不止一次出现。
  • hum "foobar 匹配但 foobardoesnt ,whearas foo bar 匹配,FoO Bar 也是如此":D

标签: regex perl match keyword space


【解决方案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);

【讨论】:

    【解决方案2】:

    这会返回正确的结果:

    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)
    

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

    【讨论】:

    • 我需要 /i 因为我不想区分大小写
    • 好的,请检查我的回复,我已将其更新为不区分大小写
    • 你可以先传入字符串然后使用my ($s, @keywords) = @_;
    • @RobEarl 是的,你是对的,这样会更好,但我假设相反的顺序,因为 OP 谈到了“采用关键字列表和字符串的函数”
    猜你喜欢
    • 2023-03-26
    • 2020-02-01
    • 2020-05-18
    • 1970-01-01
    • 2015-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-21
    相关资源
    最近更新 更多