使用正则表达式,截取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 = "[`~!@#$%^&*()+=|{}:;\\\\[\\\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]"; return Pattern.compile(regEx).matcher(str).replaceAll("").trim(); }
更新于2018-09-12
做一个小需求遇到的问题。
需要支持输入大小写字母、汉字、数字、@、.、#、-、_及其组合。
想偷个懒,就尝试将多个正则表达式拼接起来。
最后发现,通过" | " 可以将多个正则表达式拼接起来使用。
