0

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 Answers2

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
1

Regex

\/((\w+)\.(\w+))$

Regular expression visualization

Debuggex Demo

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