2012-08-17 54 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]);