I have the following String (This format for the string is generic)
abc_2012-10-18-05-37-23_prasad_hv_Complete
I want to extract only
You can use a regex to extract the data:
String input = "abc_2012-10-18-05-37-23_prasad_hv_Complete";
String output = input.replaceAll("(?i)^[a-z]+_[^_]+_(\\w+)_[a-z]+$", "$1");
You say
This format for the string is generic.
Then concatenate the elements with indexes 2 and 3 after splitting:
String str = "abc_2012-10-18-05-37-23_prasad_hv_Complete";
String[] parts = str.split("_");
String extractedResult = "";
if(parts.length > 3)
extractedResult = parts[2] + "_" + parts[3]; // prasad_hv is captured here.
May be you can try appending the strings again if you exactly know the location of them and if you are sure that locations are constant.
This will work even when you have many number of underscore characters in the string you wanted.
str.substring(str.indexOf("_", str.indexOf("_") + 1) + 1, str.lastIndexOf("_"));
What I understand by your question is that you want 3rd element to (n-1)th element of the String split by "_" to come as it is (where n is the length of array formed after splitting). So, the code would be like this:
import java.util.Arrays;
public class StringSplit {
public static final String test = "abc_2012-10-18-05-37-23_prasad_hv_Complete";
public static void main(String args[]){
String[] data = test.split("_");
System.out.println(Arrays.toString(data));
String aim = data[2];
for(int i=3;i<data.length-1;i++){
aim+="_"+data[i];
}
System.out.println(aim);
}
}
You can do like this
String token[] = myString().split("_");
String resultString = "";
for(int a=0; a<token.length-1 ;a++){
if(a == token.length-2)
resultString = resultString+token[a]
else
resultString = resultString+token[a]+"_";
}
the resultString
would be your desired string in every case