Turtle Turtle - 5 months ago 6
Java Question

Disregarding first part of split string

If I have a string like : 1234_my_string.txt is there a better way than the one provided to lop off the 1234_ so the value of the string would be equal to my_string.txt?

To be clear, I want to discard everything up to and including the first '_' in the string. The string is not neccessarily equal to "1234_my_string.txt". The length of the characters before the first '_' is not known.


String str = "1234_my_string.txt";
do foo
str == my_string.txt

Here is a working example I currently have which checks the value of str then splits and rejoins the string to get the desired result. The size of characters I want to lop off is not known. I do not think this is very efficient:

if(str != null && !str.equals("") )
String [] strParts = str.split("_");
val = "";

for (int i = 1; i < strParts.length; i++)
str += strParts[i];
str += "_";

str = str.substring(0, str.length()-1);


If you just want to get rid of everything up to and including the first _, one easy way would just be to use a regular expression and replace that section with "".


String str = "1234_my_string.txt";
str = str.replaceFirst("[^_]*_", "");
System.out.println(str);  // my_string.txt