Reputation: 7604
I have a string:
/abc/def/ghfj.doc
I would like to extract ghfj.doc
from this, i.e. the substring after the last /
, or first /
from right.
Could someone please provide some help?
Upvotes: 261
Views: 627814
Reputation: 537
Another way is to use StringUtils.substringAfterLast()
from Apache Commons Lang:
String path = "/abc/def/ghfj.doc"
String fileName = StringUtils.substringAfterLast(path, "/");
If you pass null to this method, it will return null.
If there is no match with separator, it will return empty string.
Upvotes: 39
Reputation: 302
java android
in my case
I want to change from
~/propic/........png
anything after /propic/ doesn't matter what before it
........png
finally, I found the code in Class StringUtils
this is the code
public static String substringAfter(final String str, final String separator) {
if (isEmpty(str)) {
return str;
}
if (separator == null) {
return "";
}
final int pos = str.indexOf(separator);
if (pos == 0) {
return str;
}
return str.substring(pos + separator.length());
}
Upvotes: 0
Reputation: 26743
String example = "/abc/def/ghfj.doc";
System.out.println(example.substring(example.lastIndexOf("/") + 1));
Upvotes: 402
Reputation: 9518
With Guava do this:
String id="/abc/def/ghfj.doc";
String valIfSplitIsEmpty="";
return Iterables.getLast(Splitter.on("/").split(id),valIfSplitIsEmpty);
Eventually configure the Splitter
and use
Splitter.on("/")
.trimResults()
.omitEmptyStrings()
...
Also take a look into this article on guava Splitter and this article on guava Iterables
Upvotes: 4
Reputation: 5599
In Kotlin you can use substringAfterLast
, specifying a delimiter.
val string = "/abc/def/ghfj.doc"
val result = url.substringAfterLast("/")
println(result)
// It will show ghfj.doc
From the doc:
Returns a substring after the last occurrence of delimiter. If the string does not contain the delimiter, returns missingDelimiterValue which defaults to the original string.
Upvotes: 6
Reputation: 1061
You can use Apache commons:
For substring after last occurrence use this method.
And for substring after first occurrence equivalent method is here.
Upvotes: 12
Reputation: 4418
This can also get the filename
import java.nio.file.Paths;
import java.nio.file.Path;
Path path = Paths.get("/abc/def/ghfj.doc");
System.out.println(path.getFileName().toString());
Will print ghfj.doc
Upvotes: 8
Reputation: 1
I think that would be better if we use directly the split function
String toSplit = "/abc/def/ghfj.doc";
String result[] = toSplit.split("/");
String returnValue = result[result.length - 1]; //equals "ghfj.doc"
Upvotes: 0
Reputation: 7854
what have you tried? it's very simple:
String s = "/abc/def/ghfj.doc";
s.substring(s.lastIndexOf("/") + 1)
Upvotes: 44
Reputation: 37905
A very simple implementation with 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];
Upvotes: 54