Home > Java > JavaBase > body text

How to use regular expressions to filter special characters in java

王林
Release: 2019-11-26 12:51:41
forward
3612 people have browsed it

How to use regular expressions to filter special characters in java

实例代码如下:

推荐java视频教程:java学习视频

public class FilterSpecialStr {
 
  public static void main(String[] args) {
 
    String regEx="[\n`~!@#$%^&*()+=|{}&#39;:;&#39;,\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。, 、?]";
    // 除了字母数字下划线之外的字符为非法字符
    Pattern pattern = Pattern.compile(regEx);
    // 指定设置非法字符
    // Pattern pattern = Pattern.compile("[@#]");
    String str = "123@abc {}  \n  #D     EF。";
    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());
  }
 
 
}
Copy after login

输出的结果:

过滤前的字符: 123@abc {}  
  #D     EF。
过滤后的字符: 123abcDEF

java相关文章教程:java语言入门

The above is the detailed content of How to use regular expressions to filter special characters in java. For more information, please follow other related articles on the PHP Chinese website!

source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template