我想寫一個Java的String.matches(正則表達式)方法的正則表達式以匹配文件擴展名。我嘗試過。*。ext但這不匹配以.ext結尾的文件,只是分機 然後我嘗試了.*\.ext
,這在一個正則表達式測試器中工作,但在Eclipse中我得到一個無效的轉義序列錯誤。 任何人都可以幫助我嗎? 由於Java正則表達式幫助
回答
在蝕(JAVA),正則表達式字符串需要「逃逸」:
".*\\.ext"
匹配串的點,接着是零個或多個非點和結束:
\.[^.]*$
需要注意的是,如果這是在Java字符串中,你需要轉義反斜線:
Pattern p = Pattern.compile("\\.[^.]*$");
對於這樣一個簡單的情況,你爲什麼不使用String.endsWith?
我甚至沒有想到這一點..謝謝。 – 2009-08-24 06:24:35
好的建議。 +1 – VonC 2009-08-24 06:33:06
這是一個測試程序,說明你的正則表達式使用方法:
public class Demo {
public static void main(String[] args) {
String re = "^.*\\.ext$";
String [] strings = new String[] {
"file.ext", ".ext",
"file.text", "file.ext2",
"ext"
};
for (String str : strings) {
System.out.println (str + " matches('" + re + "') is " +
(str.matches (re) ? "true" : "false"));
}
}
}
和這裏的輸出(稍微改動過的「美的」):
file.ext matches('^.*\.ext$') is true
.ext matches('^.*\.ext$') is true
file.text matches('^.*\.ext$') is false
file.ext2 matches('^.*\.ext$') is false
ext matches('^.*\.ext$') is false
但你並不真的需要那麼,一個簡單的
str.endsWith (".ext")
會做這個特定的工作。
如果需要比較是不區分大小寫(.EXT,.EXT,...)的Windows,你可以使用:
str.toLowerCase().endsWith(".ext")
比我的回答更詳細。 +1 – VonC 2009-08-24 06:34:01
- 1. Java正則表達式幫助
- 2. 正則表達式(JAVA)的幫助
- 3. 正則表達式幫助java
- 4. Java正則表達式幫助
- 5. java中的正則表達式幫助
- 6. Java - 正則表達式幫助
- 7. java的正則表達式的幫助
- 8. 邏輯幫助 - java正則表達式
- 9. java string.split()正則表達式幫助
- 10. java正則表達式幫助
- 11. 正則表達式幫助##### ##
- 12. 幫助,正則表達式
- 13. 正則表達式幫助
- 14. 正則表達式幫助
- 15. 正則表達式幫助
- 16. 正則表達式幫助
- 17. 幫助正則表達式
- 18. 正則表達式幫助
- 19. 正則表達式幫助
- 20. 正則表達式幫助
- 21. 正則表達式幫助
- 22. 正則表達式幫助
- 23. 幫助正則表達式
- 24. 正則表達式幫助
- 25. 幫助正則表達式
- 26. 正則表達式幫助
- 27. 幫助,正則表達式
- 28. 幫助,正則表達式
- 29. 幫助正則表達式?
- 30. 正則表達式幫助
謝謝,非常完美。 – 2009-08-24 06:22:43
然而,你的回答是有幫助的(這是標準),對於我們這些容易疲勞的人來說更簡潔,所以+1右回到亞:-) – paxdiablo 2009-08-24 07:01:30