2012-08-17 57 views
2

我有一個目錄列表作爲字符串的特定部分,我想檢索字符串的特定部分,唯一的一點是,因爲這是一個目錄時,它的長度可以改變如何檢索串

我想從字符串

"C:\projects\Compiler\Compiler\src\JUnit\ExampleTest.java" 
"C:\projects\ExampleTest.java" 

因此,在這兩種情況下,我想檢索檢索文件名剛ExampleTest(文件名也可以改變,所以我需要像第一.之前獲取文本和在最後\)。有沒有辦法使用像正則表達式或類似的東西來做到這一點?

+3

那豈不是最適合所有參與,如果你表現出你的努力的成果,第一,告訴我們爲什麼它沒有工作?因此,在這種情況下,[你有什麼嘗試?](http://mattgemmell.com/2008/12/08/what-have-you-tried/) – 2012-08-17 11:25:25

回答

6

爲什麼不使用Apache Commons FileNameUtils而不是編寫自己的正則表達式?從DOC:

此類定義文件名中的六個組件(例如 C:\ dev的\項目\ file.txt的):

the prefix - C:\ 
the path - dev\project\ 
the full path - C:\dev\project\ 
the name - file.txt 
the base name - file 
the extension - txt 

你是好了很多使用過這個。它直接面向朝向文件名,顯示目錄等,並且給定的,它是一種常用的,定義明確的組分,這將已被廣泛測試並邊緣情況理順等

3
new File(thePath).getName() 

int pos = thePath.lastIndexOf("\\"); 
return pos >= 0? thePath.substring(pos+1): thePath; 
1
File file = new File("C:\\projects\\ExampleTest.java"); 
System.out.println(file.getAbsoluteFile().getName()); 
1

這是c#正則表達式,它在java工作:P too.Thanks到Perl。它在組[1]

匹配
^.*\\(.*?)\..*?$ 
+1

決定使用FileNameUtils,但純粹的答案... +1 – 2012-08-17 11:50:39

1

Java代碼

String test = "C:\\projects\\Compiler\\Compiler\\src\\JUnit\\ExampleTest.java"; 
String arr[] = test.split("\\Q"+"\\"); 
System.out.println(arr[arr.length-1].split("\\.")[0]);