2

我有一个目录列表作为字符串,我想检索字符串的特定部分,唯一的是因为这是一个目录,它可以改变长度

我想从字符串中检索文件名

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

因此,在这两种情况下,我只想检索ExampleTest(文件名也可以更改,因此我需要获取第一个之前.和最后一个之后的文本\)。有没有办法使用正则表达式或类似的东西来做到这一点?

4

5 回答 5

6

为什么不使用 Apache Commons FileNameUtils而不是编写自己的正则表达式?从文档:

此类在文件名中定义了六个组件(例如 C:\dev\project\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

你用这个好多了。它直接面向文件名、目录等,并且鉴于它是一个常用的、定义明确的组件,它将经过广泛的测试并消除边缘情况等。

于 2012-08-17T11:24:37.550 回答
3
new File(thePath).getName()

或者

int pos = thePath.lastIndexOf("\\");
return pos >= 0? thePath.substring(pos+1): thePath;
于 2012-08-17T11:28:37.217 回答
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]);
于 2012-08-17T11:42:31.657 回答
1
File file = new File("C:\\projects\\ExampleTest.java");
System.out.println(file.getAbsoluteFile().getName());
于 2012-08-17T11:29:16.897 回答
1

这是正则表达式,c#它也可以在java :P中使用。感谢 .Perl它在 Group[1] 中匹配

^.*\\(.*?)\..*?$
于 2012-08-17T11:38:47.740 回答