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?

5
  • Could you post example of result you are expecting? Commented Nov 23, 2015 at 3:31
  • I expect test.dat while split[0] already returns everything before it Commented Nov 23, 2015 at 3:32
  • Do you need to use regex here? There may be better tools go get file name. Commented Nov 23, 2015 at 3:32
  • If you can tell me a better solution I wouldn't mind Commented Nov 23, 2015 at 3:33
  • Refresh page with this post and see linked duplicate at top. Commented Nov 23, 2015 at 3:34

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Yes ...if you want only file name than rather go with lastIndexOf() method ...
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();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.