我有一个字符串:

/abc/def/ghfj.doc

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

有人能帮帮忙吗?


当前回答

另一种方法是使用这个。

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

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

其他回答

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

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

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

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

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

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

医生说:

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

另一种方法是使用这个。

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));

你都试过什么? 这很简单:

String s = "/abc/def/ghfj.doc";
s.substring(s.lastIndexOf("/") + 1)