import java.io.UnsupportedEncodingException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author:ccn date:Feb 14, 2012 describe:
*/
public class T {
/**
* @param args
* @throws UnsupportedEncodingException
*/
public static void main(String[] args) throws UnsupportedEncodingException {
String input = "世界&&你好! {hello wor^ld: (1+1)=2,\\(1-1)=0,2*3=?";
System.out.println("input string--->"+input);
//查询之前对输入的特殊保留字符进行转换
String queryString = transformSolrMetacharactor(input);
System.out.println("query string---->"+queryString);
//query...
}
/**
* 转义Solr/Lucene的保留运算字符
* 保留字符有+ - && || ! ( ) { } [ ] ^ ” ~ * ? : \
* @param input
* @return 转义后的字符串
*/
public static String transformSolrMetacharactor(String input){
StringBuffer sb = new StringBuffer();
String regex = "[+\\-&|!(){}\\[\\]^\"~*?:(\\)]";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
while(matcher.find()){
matcher.appendReplacement(sb, "\\\\"+matcher.group());
}
matcher.appendTail(sb);
return sb.toString();
}
}
//-----输出结果-------
input string--->世界&&你好! {hello wor^ld: (1+1)=2,\(1-1)=0,2*3=?
query string---->世界\&\&你好\! \{hello wor\^ld\: \(1\+1\)=2,\\(1\-1\)=0,2\*3=\?