我有一个字符串:

/abc/def/ghfj.doc

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

有人能帮帮忙吗?


当前回答

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

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

医生说:

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

其他回答

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

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。如果与分隔符不匹配,则返回空字符串。

String example = "/abc/def/ghfj.doc";
System.out.println(example.substring(example.lastIndexOf("/") + 1));

你可以使用Apache commons:

对于最后一次出现之后的子字符串使用此方法。

对于第一次出现后的子字符串,等效方法在这里。

用番石榴这样做:

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

最终配置并使用Splitter

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

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