簡體   English   中英

正則表達式檢查字符串是否包含非數字失敗

[英]Regex check to see if a String contains non digit fails

為什么這會失敗?

String n = "h107";
if (n.matches("\\D+")) {
  System.out.println("non digit in it");
}

我有一個晚上睡覺,我仍然沒有得到它。 我現在得到了解決方案:

if (n.matches(".*\\D+.*")) {

但在我(可能缺乏知識)中,第一個也應該匹配。 如果它必須匹配一個完整的String,那么行開頭的'^'字符的重點是什么。

這是.matches()的反復出現的問題:它被錯誤命名。 它不進行正則表達式匹配。 而問題在於,甚至其他語言也成為了這種錯誤的犧牲品(python就是一個例子)。

問題是它會嘗試匹配您的整個輸入。

使用一個Pattern ,一個Matcher.find()代替( .find() 沒有真正的正則表達式匹配,即發現任何地方匹配輸入文本):

private static final Pattern NONDIGIT = Pattern.compile("\\D");

// in code
if (NONDIGIT.matcher(n).find())
    // there is a non digit

實際上你應該使用Pattern ; String.matches() 每次都會重新編譯一個模式。 使用Pattern ,它只編譯一次。

如果整個字符串與模式匹配,則String.matches返回true。 只需將正則表達式更改為\\d+ ,如果整個字符串由數字組成,則返回true:

String n = "h107";
if (!n.matches("\\d+")) {
     System.out.println("non digit in it");
}

暫無
暫無

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

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