首页 > 解决方案 > 正则表达式 - 列出与模式不匹配的字符

问题描述

我有下面的正则表达式,它说明给定的输入是否与模式匹配

String input="The input here @$%/";
String pattern="[a-zA-Z0-9,.\\s]*";
if (!input.matches(pattern)) {
System.out.println("not matched");
}else{
  System.out.println("matched");
}

我能知道如何增强它以列出输入中与模式不匹配的字符吗?例如这里@$%/

标签: javaregex

解决方案


正如anubhava 在评论中已经提到的那样,只需使用input.replaceAll(pattern, "").

演示:

class Main {
    public static void main(String[] args) {
        String input = "The input here @$%/";
        String pattern = "[a-zA-Z0-9,.\\s]*";
        String nonMatching = input.replaceAll(pattern, "");
        System.out.println(nonMatching);
    }
}

输出:

@$%/

推荐阅读