gpt4 book ai didi

regex - 实现 Google 搜索运算符

转载 作者:行者123 更新时间:2023-12-01 09:02:46 26 4
gpt4 key购买 nike

Google 目前在搜索中使用 site:is: 等关键字(第二个示例来自 Gmail)。我正在尝试开发一个类似的系统,并且想知道如何最好地识别和处理这些术语。为简单起见,假设正在使用一种 OO 语言(Ruby、Python、Java、C# 等)。

目前,我的计划是为每个关键字创建一个单独的类。这些类有一个优先值和三个方法:

  1. isRelevant(String searchPhrase):如果搜索短语与类的过滤器匹配,则返回 true。
  2. getResults(String searchPhrase):返回基于搜索短语的结果列表。
  3. reviseSearch(String searchPhrase):返回搜索短语的修改版本。这通常会删除匹配项以避免它被优先级较低的实例再次处理,但也可能会添加文本或完全清除字符串。

然后,调用方法将遍历这些关键字过滤器,直到搜索短语为空或不再有过滤器(在后一种情况下,它将恢复为正常搜索行为)。

因此,问题是:这是执行此操作的最有效方法,还是有更合适的方法?一些细节仍然需要弄清楚,但这是朝着正确方向迈出的一步吗?

最佳答案

基础知识

示例字符串:

foo:(hello world) bar:(-{bad things}) email:something@email.tld another:weird characters +=2{-52!%#^ final:end

用正则表达式拆分:

/\s+(?=\w+:)/

返回数组:

[
'foo:(hello world)',
'bar:(-{bad things})',
'email:something@email.tld',
'another:weird characters +=2{-52!%#^',
'final:end'
]

正则解释:

\s+     one or more spaces
(?= followed by (positive lookahead)
\w+ one or more word characters
: literal `:' (colon character)
)

用法:

遍历数组,在 :(冒号)处拆分每个元素。左侧的 key 可用于调用函数,右侧的 value 可作为函数参数传递。这应该会让您从这里走上正轨,无论您想做什么。

ruby 用法示例

搜索.rb

# Search class
class Search

def initialize(query)
@query = query
end

def foo(input)
"foo has #{input}"
end

def bar(input)
"bar has #{input}"
end

def email(input)
"email has #{input}"
end

def another(input)
"another has #{input}"
end

def final(input)
"final has #{input}"
end

def exec
@query.split(/\s+(?=\w+:)/).each do |e|
method, arg = e.split(/:/)
puts send(method, arg) if respond_to? method
end
end

end

使用搜索.rb

q = "foo:(hello world) bar:(-{bad things}) email:something@email.tld another:weird characters +=2{-52!%#^ final:end";
s = Search.new(q)
s.exec

输出

foo has (hello world)
bar has (-{bad things})
email has something@email.tld
another has weird characters +=2{-52!%#^
final has end

关于regex - 实现 Google 搜索运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2328926/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com