0

我正在扫描不同项目的名称和描述,以查看是否有任何关键字匹配。

在下面的代码中,它将返回诸如“googler”或“applecobbler”之类的内容,而我想要做的只是获得完全匹配:

[name, description].join(" ").downcase.scan(/apple|microsoft|google/)

我该怎么做?

4

4 回答 4

6

我的正则表达式技能很弱,但我认为您需要使用单词边界:

[name, description].join(" ").downcase.scan(/\b(apple|microsoft|google)\b/)

红字样例

于 2012-11-27T16:35:32.057 回答
3

取决于您想要什么信息,但如果您只想要完全匹配,则比较部分不需要正则表达式。只需比较相关的字符串。

splitted_strings = [name, description].join(" ").downcase.split(/\b/)

splitted_strings & %w[apple microsoft google]
# => the words that match given in the order of appearance
于 2012-11-27T17:43:06.097 回答
0

\b在您的正则表达式 ( )中添加适当的边界实体。也可以使用#grep方法。而不是加入:

array.grep(your_regexp)
于 2012-11-27T16:36:38.960 回答
0

看看这个问题,以及我想做这些事情的情况,这就是我要为一个实际程序做的事情,我有来源列表及其相关文本,并且想知道点击率,我会可能会这样写:

require 'pp'

names = ['From: Apple', 'From: Microsoft', 'From: Google.com']
descriptions = [
  '"an apple a day..."',
  'Microsoft Excel flight simulator... according to Microsoft',
  'Searches of Google revealed multiple hits for "google"'
]
targets = %w[apple microsoft google]
regex = /\b(?:#{ Regexp.union(targets).source })\b/i

names.zip(descriptions) do |n,d|
  name_hits, description_hits = [n, d].map{ |s| s.scan(regex) }
  pp [name_hits, description_hits]
end

哪个输出:

[["Apple"], ["apple"]]
[["Microsoft"], ["Microsoft", "Microsoft"]]
[["Google"], ["Google", "google"]]

这会让我知道单词的字母大小写,所以我可以尝试将苹果水果与 Apple the company 区分开来,并获得字数,帮助显示文本的相关性。

regex看起来像:

/\b(?:apple|microsoft|google)\b/i

它不区分大小写,但scan会以原始大小写返回单词。

namesdescriptions并且targets都可能来自数据库或单独的文件,有助于将数据与代码分开,并且需要在目标更改时修改代码。我会使用目标词列表并使用 Regexp.union 来快速构建模式。

于 2012-11-27T17:25:20.380 回答