如何从 google URL 中查找搜索词

how to find search word from google URL

我正在 Google 中搜索一个词 (Rest call)。我有三个 URL 用于一次搜索。

  1. 在多功能框(我们点击网址的浏览器输入框)中搜索显示 URL 如下。(我的默认搜索引擎是 Google)

    https://www.google.co.in/search?q=rest+call+in+java&ie=utf-8&oe=utf-8&gws_rd=cr&ei=BaaMVoLbHIKEuwT_oIQI
    
  2. 从Google主页搜索显示URL如下。

    https://www.google.co.in/?gws_rd=ssl#q=rest%20call%20in%20java
    
  3. 从 Google 搜索,但这次我从 Google 中显示的结果页面中单击 Google 徽标(它转到 https://www.google.co.in/webhp?hl=en ), 在这个 google 页面搜索后显示 URL 如下,

    https://www.google.co.in/webhp?hl=en#hl=en-IN&q=rest+call+in+java
    

以上三个 url 对于相同的查询文本显示相同的结果,但是三个不同的 URLs。

我想获取在 Google 文本框中搜索的单词。如何从 Java.

中获取这个词

我知道如果我们使用字符串正则表达式,我们可以得到,但是对于相同的搜索有三种类型的 URLs。

所有 URL 使用相同的模式来指定搜索词,其在 q 查询字符串下。您可以只使用 String.indexOf 方法并操纵此模式来获取搜索词。

    //this is the url, it can be any of the 3 variants 
    String s = "https://www.google.co.in/search?q=rest+call+in+java&ie=utf-8&oe=utf-8&gws_rd=cr&ei=BaaMVoLbHIKEuwT_oIQI";

    //find the beginning of the searched term 
    int i = s.indexOf("q=");

    //find the end of the searched term
    int j = s.indexOf("&", i);
    j = j == -1 ? s.length() : j;

    //extract the searched term and decode
    String q = URLDecoder.decode(s.substring(i + 2, j));

正如您提到的,另一种方法是使用 regex。您不必为单独的 URL 使用单独的 regex。一个 regex 就可以了。

    //this is the url, it can be any of the 3 variants 
    String s = "https://www.google.co.in/search?q=rest+call+in+java&ie=utf-8&oe=utf-8&gws_rd=cr&ei=BaaMVoLbHIKEuwT_oIQI"; 

    //prepare the regex
    Pattern pattern = Pattern.compile("q=(.*?)(?:&|$)");
    Matcher matcher = pattern.matcher(s);

    //extract and decode
    String q = matcher.find() ? URLDecoder.decode(matcher.group(1)) : "";