程序片段如下,用C#编写,在C#下运行正常,如何改写成JAVA呢?
public string GetSearchKeyWords(string strQuery)
{
string result = "";
string pattern = "\\b\\w*p=(?!u)\\w*\\b|\\b\\w*q=(?!u)\\w*\\b|\\b\\w*qs=(?!u)\\w*\\b"
+ "|\\b\\w*encquery=(?!u)\\w*\\b|\\b\\w*k=(?!u)\\w*\\b\\b\\w*qt=(?!u)\\w*\\b"
+ "|\\b\\w*query=(?!u)\\w*\\b|\\b\\w*rdata=(?!u)\\w*\\b|\\b\\w*search_word=(?!u)\\w*\\b"
+ "|\\b\\w*szukaj|terms=(?!u)\\w*\\b\\b\\w*text=(?!u)\\w*\\b|\\b\\w*wd=(?!u)\\w*\\b|\\b\\w*words=(?!u)\\w*\\b";
foreach (Match m in Regex.Matches(strQuery, pattern)) {
// get the matched string
string x = m.ToString();
x = x.Substring(1, x.Length - 1);
// collect all text
result += x;
}
return result.Replace("=", "");
}
输入: http://www.google.com/url?sa=t&source=web&cd=7&ved=0CEQQFjAG&url=http%3A%2F%2Fwww.example.com%2F&rct=j&q=codeproject.com=uSLVTMm0JYXNhAewqbzjBA&usg=AFQjCNFtfSFIuj4fxnl8bD_bR2NgzDePGw&cad=rja
正确输出:
codeproject.com
源代码片段出自:http://www.codeproject.com/Tips/127681/Get-search-key-word-from-the-referrer-url
以下是我的改写:
import java.net.*;
import java.io.*;
import java.util.regex.*;
public class aa {
public static void GetSearchKeyWords(String strQuery) throws IOException {
Pattern pattern = Pattern.compile("\\b\\w*p=(?!u)\\w*\\b|\\b\\w*q=(?!u)\\w*\\b|\\b\\w*qs=(?!u)\\w*\\b"
+ "|\\b\\w*encquery=(?!u)\\w*\\b|\\b\\w*k=(?!u)\\w*\\b\\b\\w*qt=(?!u)\\w*\\b"
+ "|\\b\\w*query=(?!u)\\w*\\b|\\b\\w*rdata=(?!u)\\w*\\b|\\b\\w*search_word=(?!u)\\w*\\b"
+ "|\\b\\w*szukaj|terms=(?!u)\\w*\\b\\b\\w*text=(?!u)\\w*\\b|\\b\\w*wd=(?!u)\\w*\\b|\\b\\w*words=(?!u)\\w*\\b");
String s = strQuery;
Matcher matcher = pattern.matcher(s);
if (matcher.find()){
s = matcher.group();
s = s.substring(1, s.length() - 1);
s = s.replace("=", "");
System.out.println(s);
}
}
public static void main(String[] args) throws Exception {
GetSearchKeyWords("http://www.google.com/url?sa=t&source=web&cd=7&ved=0CEQQFjAG&url=http%3A%2F%2Fwww.example.com%2F&rct=j&q=codeproject.com=uSLVTMm0JYXNhAewqbzjBA&usg=AFQjCNFtfSFIuj4fxnl8bD_bR2NgzDePGw&cad=rja");
}
}
错误输出:codeprojec .com不见了.