我有一个字符串:

/abc/def/ghfj.doc

我想从中提取ghfj.doc,即在最后一个/之后的子字符串,或从右边的第一个/。

有人能帮帮忙吗?


当前回答

我认为如果我们直接使用分裂函数会更好

String toSplit = "/abc/def/ghfj.doc";

String result[] = toSplit.split("/");

String returnValue = result[result.length - 1]; //equals "ghfj.doc"

其他回答

另一种方法是使用这个。

String path = "/abc/def/ghfj.doc"
String fileName = StringUtils.substringAfterLast(path, "/");

如果你将null传递给这个方法,它将返回null。如果与分隔符不匹配,则返回空字符串。

在Kotlin中,您可以使用substringAfterLast,指定分隔符。

val string = "/abc/def/ghfj.doc"
val result = url.substringAfterLast("/")
println(result)
// It will show ghfj.doc

医生说:

返回分隔符最后出现后的子字符串。如果字符串不包含分隔符,则返回默认为原始字符串的missingDelimiterValue。

用番石榴这样做:

String id="/abc/def/ghfj.doc";
String valIfSplitIsEmpty="";
return Iterables.getLast(Splitter.on("/").split(id),valIfSplitIsEmpty);

最终配置并使用Splitter

Splitter.on("/")
.trimResults()
.omitEmptyStrings()
...

还可以看看这篇关于番石榴分离器的文章和这篇关于番石榴迭代的文章

一个非常简单的String.split()实现:

String path = "/abc/def/ghfj.doc";
// Split path into segments
String segments[] = path.split("/");
// Grab the last segment
String document = segments[segments.length - 1];

我认为如果我们直接使用分裂函数会更好

String toSplit = "/abc/def/ghfj.doc";

String result[] = toSplit.split("/");

String returnValue = result[result.length - 1]; //equals "ghfj.doc"