2011-10-07 62 views
12

我想測試一個字符串是否以數字結尾。我期望以下Java行可以打印出真實的。爲什麼它打印錯誤?正則表達式來測試一個字符串是否以數字結尾

System.out.println("I end with a number 4".matches("\\d$")); 
+0

這也可能與你的問題:http://stackoverflow.com/questions/627545/java-regexp-problem-www-vs-www – AdrianoKF

回答

8

在Java正則表達式,有(找到一個匹配的字符串的任何地方)和Matcher.matches()Matcher.find()之間的差異(符合整個字符串)。

字符串只有一個matches()方法(實施相當於此代碼:Pattern.compile(pattern).matcher(this).matches();),所以你需要創建一個完整的字符串相匹配的模式:

System.out.println("I end with a number 4".matches("^.*\\d$")); 
+0

其實,更簡單: System.out.println(「我以數字4結尾」.matches(「。* \\ d」)); 但'$'應該表示我不必在開頭指定。*。 爲什麼最後沒有'$'? – Thor

+0

額外的退格刪除了退出行爲。因此「^。* \\ d $」可能不起作用。你可以在這樣的在線正則表達式測試中測試:http://www.regexplanet.com/simple/index.html – Kash

+0

@Kash在Java中,額外的退格是必要的 –

15

你的正則表達式不會匹配整個字符串,但只最後一部分。嘗試下面的代碼,它應該很好地工作,因爲它匹配整個字符串。 http://www.regexplanet.com/simple/index.html

System.out.println("I end with a number 4".matches("^.+?\\d$")); 

您可以在線正則表達式測試儀進行快速檢查像這樣進行測試。這也給你你應該在Java代碼中使用適當的轉義結果。

。+將確保數字之前至少有一個字符。 The 將確保它做一個懶惰的匹配,而不是一個貪婪的匹配。

+0

在這種情況下做一個懶惰的匹配是沒有意義的。我們*希望*。+'立即吞噬整個字符串。然後它將退回一個位置,將最後一個字符與'\ d'進行比較,這是我們唯一關心的事情。 –

-1

試試這個:

System.out.println("I end with a number 4".matches(".*\\d\$")); 
+0

不會編譯,'\ $'在Java中是非法的 –

1
System.out.println("I end with a number 4".matches(".*\\d")); // prints true 

String s = "I end with a number 4"; 
System.out.println(Character.isDigit(s.charAt(s.length()-1))); // prints true 
2

您的正則表達式是slightly off。試試這個:

System.out.println("I end with a number 4".matches("^.*\\d$")); 

你也可以簡單地測試這樣的,如果你正在評估在一個時間線:

System.out.println("I end with a number 4".matches(".*\\d")); 

你的原始表達式,而不*只測試看串是否是一個數字並沒有考慮可能在該數字之前的文本。這就是爲什麼它總是假的。

以下不計算爲真:

System.out.println("4".matches("^\\d$")); 
相關問題