繁体   English   中英

如何检索字符串的特定部分

[英]How to retrieve particular part of string

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

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

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

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

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

该类定义了文件名中的六个组件(例如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 

使用它你会好很多。 它直接面向文件名,目录等,并且鉴于它是一种常用的,定义明确的组件,它已经过广泛测试,并且可以解决边缘情况等问题。

new File(thePath).getName()

要么

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

这是c#的正则表达式,它适用于java :P too.Thanks to Perl它匹配Group [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]);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM