2009-08-24 59 views
1

我想寫一個Java的String.matches(正則表達式)方法的正則表達式以匹配文件擴展名。我嘗試過。*。ext但這不匹配以.ext結尾的文件,只是分機 然後我嘗試了.*\.ext,這在一個正則表達式測試器中工作,但在Eclipse中我得到一個無效的轉義序列錯誤。 任何人都可以幫助我嗎? 由於Java正則表達式幫助

回答

2

在蝕(JAVA),正則表達式字符串需要「逃逸」:

".*\\.ext" 
+0

謝謝,非常完美。 – 2009-08-24 06:22:43

+0

然而,你的回答是有幫助的(這是標準),對於我們這些容易疲勞的人來說更簡潔,所以+1右回到亞:-) – paxdiablo 2009-08-24 07:01:30

0

匹配串的點,接着是零個或多個非點和結束:

\.[^.]*$ 

需要注意的是,如果這是在Java字符串中,你需要轉義反斜線:

Pattern p = Pattern.compile("\\.[^.]*$"); 
2

對於這樣一個簡單的情況,你爲什麼不使用String.endsWith

+0

我甚至沒有想到這一點..謝謝。 – 2009-08-24 06:24:35

+0

好的建議。 +1 – VonC 2009-08-24 06:33:06

4

這是一個測試程序,說明你的正則表達式使用方法:

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") 
+0

比我的回答更詳細。 +1 – VonC 2009-08-24 06:34:01