I'm trying to slpit the string /home/user/test.dat
I use String[] split = file.split("(?!.*/)"); but split[1] only returns the first character instead of the whole file name. How would I edit my regex so that it returns everything past the last forward slash?
2 Answers
Unless there's some compelling reason to use a regular expression, I would use the simple String.lastIndexOf(int). Something like,
String file = "/a/b/c/d/e/test.dat";
int afterSlash = file.lastIndexOf('/');
if (afterSlash > -1) {
file = file.substring(afterSlash + 1);
}
System.out.println(file);
Output of above being (the requested)
test.dat
1 Comment
Naruto
Yes ...if you want only file name than rather go with lastIndexOf() method ...
Regex
\/((\w+)\.(\w+))$

However, since you are using Java simply load the string into the File helper which can pull out the filename:
Java
Path p = Paths.get("C:\\Hello\\AnotherFolder\\The File Name.PDF");
String file = p.getFileName().toString();
test.datwhile split[0] already returns everything before it