Extract everything after slash or backslash using Java

Viewed 34

I am a newbie in regex and trying to figure out how I could split this string in Java:

My input string can be of one of the following forms:

String myStr = "%abc%\xyz\test.exe";
String myStr = "%abc%/xyz/test.exe";
String myStr = test.exe

I am trying to extract "test.exe" in every case.

I am not able to split the input string correctly as if I use the following:

System.out.println(Arrays.toString(myStr.split("[^\\/]+$")));

I get:

[%abc%/xyz/]

Which is part of the string I don't want. Any idea how I can get the delimiter itself in this case with Java string split?

2 Answers

You can just replace everything upto last / or \ using replaceFirst:

String myStr = "%abc%\\xyz\\test.exe";
myStr = myStr.replaceFirst("^.*[/\\\\]", "");
//=> "test.exe"

myStr = "%abc%/xyz/test.exe";
myStr = myStr.replaceFirst("^.*[/\\\\]", "");
//=> "test.exe"

myStr = "test.exe";
myStr = myStr.replaceFirst("^.*[/\\\\]", "");
//=> "test.exe"

RegEx Demo

If you are using Java 7+ you don't need regex.

Code:

String myStr = "%abc%\\xyz\\test.exe";
String myStr1 = "%abc%/xyz/test.exe";
String myStr2 = "test.exe";
System.out.println(Paths.get(myStr).getFileName().toString());
System.out.println(Paths.get(myStr1).getFileName().toString());
System.out.println(Paths.get(myStr2).getFileName().toString());

Output:

test.exe
test.exe
test.exe
Related