Java正则表达式过滤并消除非法字符

2014-05-31· 11366 次浏览
## 过滤并消除非法字符示例 ```java // 除了字母数字下划线之外的字符为非法字符 Pattern pattern = Pattern.compile("[^a-zA-Z0-9]"); // 指定设置非法字符 // Pattern pattern = Pattern.compile("[@#]"); String str = "123@abc#DEF"; Matcher matcher = pattern.matcher(str); StringBuffer buffer = new StringBuffer(); // 如果找到非法字符 while (matcher.find()) { // 如果里面包含非法字符如冒号双引号等,那么就把他们消去,并把非法字符前面的字符放到缓冲区 matcher.appendReplacement(buffer, ""); } // 将剩余的合法部分添加到缓冲区 matcher.appendTail(buffer); System.out.println("您的输入为: " + str); System.out.println("合法的输出为: " + buffer.toString()); ``` 输出: ``` 您的输入为: 123@abc#DEF 合法的输出为: 123abcDEF ``` ## 批量替换的示例 ``` Pattern p = Pattern.compile("cat"); Matcher m = p.matcher("one cat two cats in the yard"); StringBuffer sb = new StringBuffer(); while (m.find()) { m.appendReplacement(sb, "dog"); } m.appendTail(sb); System.out.println(sb.toString()); ``` 输出: ``` one dog two dogs in the yard ```