Implementing Google search operators

前端 未结 1 1024
天命终不由人
天命终不由人 2020-12-18 11:04

Google currently uses keywords such as site: or is: in searches (the second example is from Gmail). I\'m trying to develop a similar system and am

相关标签:
1条回答
  • 2020-12-18 11:39

    Basics

    sample string:

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

    split with regex:

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

    return array:

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

    regex explanation:

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

    usage:

    Iterate through the array, split each element at : (colon). The left side key could be used to call a function and the right side value could be passed as the function parameter. This should pretty much put you on track for whatever you want to do from here.

    Example ruby usage

    search.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
    

    use search.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
    

    output

    foo has (hello world)
    bar has (-{bad things})
    email has something@email.tld
    another has weird characters +=2{-52!%#^
    final has end
    
    0 讨论(0)
提交回复
热议问题