Java - 从右侧剪切一个字符串直到特定字符

Java - Cut a String from the right side till specific character

我有以下字符串,文件路径如下:

/Users/Fabian/Desktop/R5X5.mps

我现在只想获取文件名的含义 - 从右侧到“/”的所有内容。

In that case: R5X5.mps

最有效的方法是什么?

这可以用本机 java 方法解决吗?还是我需要构建一个正则表达式?

使用正则表达式。非常简单:

String last = str.replaceAll(".*/", "");

这个正则表达式表示 "everything up and including a slash",它没有被替换(实际上是 "deleting")。

我认为没有人会使用 "building" 这个词来描述键入 ".*/" 所需的努力。

I do now want to just geht the filename meaning

为此使用适当的 class。 Java 提供例如:

String name = new File("/Users/Fabian/Desktop/R5X5.mps").getName();

您也可以通过

获得类似的结果
String path = "/Users/Fabian/Desktop/R5X5.mps";
String name = path.substring(path.lastIndexOf("/") +1); // "+1" since we don't
                                                        // want to include `/` in result

(本质上就是 File#getName 所做的)

在我看来,使用 FilenameUtils.getName(String filename) is the best way. The FilenameUtils class is a part of Apache Commons IO

根据文档,方法 "will handle a file in either Unix or Windows format"。 "The text after the last forward or backslash is returned" 作为字符串对象。

String filename = "/Users/Fabian/Desktop/R5X5.mps";
String name = FilenameUtils.getName(filename);
System.out.println(name);

以上代码打印 R5X5.mps