Regex-列出与模式不匹配的字符



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

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

我能知道如何增强它来列出输入中与模式不匹配的字符吗。例如此处@$%/

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

输出:

@$%/

使用

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

请参阅正则表达式证明。

解释

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

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

最新更新