Java模組 -- String字串操作(數字,漢字,特殊符號過濾/擷取)
阿新 • • 發佈:2019-02-03
使用正則表示式,擷取String字串中的數字、漢字,以及過濾特殊符號
/**
* 提取字串中的數字
*
* @param number
* @return
* @throws Exception
*/
public String numberIntercept(String number) throws Exception {
return Pattern.compile("[^0-9]").matcher(number).replaceAll("");
}
/**
* 提取字串中所有的漢字
*
* @param str
* @return
* @throws Exception
*/
public String intercept(String str) throws Exception {
String regex = "[\u4E00-\u9FA5]";//漢字
Matcher matcher = Pattern.compile(regex).matcher(str);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
sb.append(matcher.group());
}
return sb.toString();
}
/**
* 過濾設定的特殊符號
*
* @param str
* @return
* @throws Exception
*/
public String filtration(String str) throws Exception {
String regEx = "[` [email protected]#$%^&*()+=|{}:;\\\\[\\\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]";
return Pattern.compile(regEx).matcher(str).replaceAll("").trim();
}
更新於2018-09-12
做一個小需求遇到的問題。
需要支援輸入大小寫字母、漢字、數字、@、.、#、-、_及其組合。
想偷個懶,就嘗試將多個正則表示式拼接起來。
最後發現,通過" | " 可以將多個正則表示式拼接起來使用。