Issue
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?
Solution
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"
Answered By - anubhava
Answer Checked By - Timothy Miller (JavaFixing Admin)