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?
Asked
Active
Viewed 57 times
0

Peter Bucher
- 49
- 7
-
Could you post example of result you are expecting? – Pshemo Nov 23 '15 at 03:31
-
I expect `test.dat` while split[0] already returns everything before it – Peter Bucher Nov 23 '15 at 03:32
-
Do you need to use regex here? There may be better tools go get file name. – Pshemo Nov 23 '15 at 03:32
-
If you can tell me a better solution I wouldn't mind – Peter Bucher Nov 23 '15 at 03:33
-
Refresh page with this post and see linked duplicate at top. – Pshemo Nov 23 '15 at 03:34
2 Answers
2
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

Elliott Frisch
- 198,278
- 20
- 158
- 249
-
1Yes ...if you want only file name than rather go with lastIndexOf() method ... – Naruto Nov 23 '15 at 03:36
1
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();

abc123
- 17,855
- 7
- 52
- 82