Skip to content

Instantly share code, notes, and snippets.

@aliang
Created June 20, 2011 22:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save aliang/1036704 to your computer and use it in GitHub Desktop.
Save aliang/1036704 to your computer and use it in GitHub Desktop.
search query string parser, google-ish
# via http://jablan.radioni.ca/post/4982485974/parsing-search-query-in-ruby
def parse_query s
s.scan(/((\S+)\:\s?)?([+-])?(("(.+?)")|(\S+))/).map{|match|
Hash[
[nil, :prefix, :plusminus, nil, nil, :phrase, :word].zip(match).select(&:all?)
]
}
end
parse_query 'foo +bar -baz "dev pro talk" site:devprotalk.com category:cat1'
# => [
# {:word=>"foo"},
# {:plusminus=>"+", :word=>"bar"},
# {:plusminus=>"-", :word=>"baz"},
# {:phrase=>"dev pro talk"},
# {:prefix=>"site", :word=>"devprotalk.com"},
# {:prefix=>"category", :word=>"cat1"}
# ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment