0

我有一个类似的数组:

["Rob Meyer", "Michelle Preston"]

我想搜索rob or Rob, or meyer or Meyer数组中任何“单词”的出现,没有字符,只有单词,不区分大小写。

那么我该怎么做呢?include?寻找完全匹配。我在这里寻找更灵活的东西。

4

4 回答 4

2

那是你要找的吗?

query = 'rob'
["Rob Meyer", "Michelle Preston"].any?{|e| e =~ /\b#{query}\b/i}
于 2013-05-02T12:47:14.867 回答
1

预编译单词列表。

words = ["Rob Meyer", "Michelle Preston"].flat_map{|s| s.downcase.scan(/\w+/)}

words.include?("Rob".downcase) # => true
于 2013-05-02T12:50:15.650 回答
0

I do this sort of thing often:

names = ["Rob Meyer", "Michelle Preston"]

targets = %w[rob meyer]
regex = /\b(?:#{ Regexp.union(targets).source })\b/i
# => /\b(?:rob|meyer)\b/i

names.select{ |name| name[regex] }

Which returns an array of the names that hit:

[
    [0] "Rob Meyer"
]

The reason I use Regexp.union is it's trivial to take a huge list of possible targets, instantly create a pattern to search for them, then search many megabytes of text for hits, all running at the speed of the regex engine, without iterations. It's about as fast as we can search in Ruby.

name[regex] is the basis for generating a true/false value. Changing it to !!name[regex] will return a boolean true/false value.

Instead of embedding it in a select which grabs the names with a hit, it could be done inside a loop with a conditional:

names.each do |name|
  if name[regex]
    puts "got a hit for '#{ name }'"
  end
end

Which outputs:

got a hit for 'Rob Meyer'
于 2013-05-02T13:50:33.017 回答
0

看起来好像您正在寻找匹配操作。Ruby 允许您使用正则表达式 (regex)。

阅读match()方法,我相信你会找到你需要的。

在 Ruby 中使用正则表达式时,在表达式后面加上“/i”将使其不区分大小写。

我通常去http://ruby-doc.org/查找 Ruby 语言细节。

祝你好运!

于 2013-05-02T12:54:09.007 回答