簡體   English   中英

正則表達式 - 列出與模式不匹配的字符

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

我有下面的正則表達式,它說明給定的輸入是否與模式匹配

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

Output:

@$%/

利用

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM