简体   繁体   English

如何在字符串中查找关键字

[英]How to find a keyword in a string

Users send in smses which must include a keyword. 用户发送必须包含关键字的smses。 This keyword is then used to find a business. 然后,此关键字用于查找业务。

The instruction is to use the keyword at the start of the sentence. 该指令是在句子的开头使用关键字。

I know some users won't use the keyword at the beginning or will add tags (# @ -) or punctuation (keyword.) to the keyword. 我知道有些用户不会在开头使用关键字,或者会在关键字中添加标签(#@ - )或标点符号(keyword。)。

What is an efficient way to look for this keyword and for the business? 查找此关键字和业务的有效方法是什么?

My attempt: 我的尝试:

scrubbed_message = msg.gsub("\"", "").gsub("\'", "").gsub("#", "").gsub("-", "").gsub(",", "").gsub(".", "").gsub("@", "").split.join(" ")
tag = scrubbed_msg.split[0]
 if @business = Business.where(tag: tag).first
  log_message(@business)
 else
  scrubbed_msg.split.each do |w|
  if @business = Business.where(tag: w).first
   log_message(@business)
  end
 end
end

You can use Regexp match to filter all unnecessary characters out of the String , then use #reduce method on the Array git from splitted string to get the first occurience of a record with tag field matched to a keyword, in the exmaple: keyword, tag1, tag2 : 您可以使用Regexp匹配来过滤String所有不必要的字符,然后在#reduce字符串的Array git上使用#reduce方法,以获得带有与关键字匹配的标记字段的记录的第一次出现,在exmaple: keyword,tag1中,tag2

msg = "key.w,ord tag-1'\n\"tag2"
# => "key.w,ord tag-1'\n\"tag2"
scrubbed = msg.gsub(/[#'"\-\.,@]/, "").split
# => ["keyword", "tag1", "tag2"]
@business = scrubbed.reduce(nil) do| sum, tag |
   sum || Business.where(tag: tag).first
end
# => Record tag: keyword
# => Record tag: tag1 if on record with keyword found

Instead of which characters you want to remove from the string, I suggest to use a whitelist approach specifying which characters you want to keep, for example alphanumeric characters: 我建议使用白名单方法来指定要保留哪些字符,例如字母数字字符,而不是要从字符串中删除哪些字符:

sms = "#keyword and the rest"
clean_sms = sms.scan(/[\p{Alnum}]+/)
# => ["keyword", "and", "the", "rest"]

And then, if I got right what you are trying to do, to find the business you are looking for you could do something like this: 然后,如果我做对了你想要做的事情,找到你正在寻找的业务,你可以这样做:

first_existing_tag = clean_sms.find do |tag| 
  Business.exists?(tag: tag)
end

@business = Business.where(tag: first_existing_tag).first
log_message(@business)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM