简体   繁体   中英

How to find a keyword in a string

Users send in smses which must include a keyword. 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.

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 :

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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