Splitting search terms

The other day I wanted to break up a search string into its constituent parts. We’re not supporting any fancy operators, but we did want to allow phrases to be specified in double quotes. It’s an easy enough operation, but I googled to see if anyone was offering a particularly efficient way to do that in ruby.

Nothing came up and since I’ve not posted in a while I thought I’d offer it for anyone else in that situation.

def split_params(params)
  # Find all phrases enclosed in quotes and pull
  # them into a flat array of phrases
  phrases = params.scan(/"(.*?)"/).flatten

  # Remove those phrases from the original string
  left_over = params.gsub(/"(.*?)"/, "").squeeze(" ").strip

  # Break up the remaining keywords on whitespace
  keywords = left_over.split(/ /)

  # Return one single array of key phrases
  keywords + phrases

Tags: , ,

1 comment

  1. After a lot of digging, I finally made my way to your post. I’m writing an “acts_as_zoom” plugin to interface with ruby-zoom queries (i.e. Z39.50 or in my case a Zebra server) and had the exact same problem that you mention here. I just want to split on words or quoted phrases and have an array of search terms.

    Wish I had found your post a few hours ago!