简体   繁体   English

正则表达式 - 列出与模式不匹配的字符

[英]Regex - list the characters which are not matching the pattern

I have below regex which says if the given input matches the pattern or not我有下面的正则表达式,它说明给定的输入是否与模式匹配

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");
}

Can i know how it can be enhanced to list the characters in the input, which are not matching the pattern.我能知道如何增强它以列出输入中与模式不匹配的字符吗? Eg here @$%/例如这里@$%/

As anubhava has already mentioned in the comment , just use input.replaceAll(pattern, "") .正如anubhava 在评论中已经提到的那样,只需使用input.replaceAll(pattern, "")

Demo:演示:

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);
    }
}

Output: Output:

@$%/

Use利用

[^a-zA-Z0-9,.\s]

See regex proof .请参阅正则表达式证明

EXPLANATION解释

 [^a-zA-Z0-9,.\s]         any character except: 'a' to 'z', 'A' to
                           'Z', '0' to '9', ',', '.', whitespace (\n,
                           \r, \t, \f, and " ")

Java code snippet : Java 代码片段

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Example {
    public static void main(String[] args) {
        final String regex = "[^a-zA-Z0-9,.\\s]";
        final String string = "The input here @$%/";
        
        final Pattern pattern = Pattern.compile(regex);
        final Matcher matcher = pattern.matcher(string);
        
        while (matcher.find()) {
            System.out.println(matcher.group(0));
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM