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 prasad_hv
. How do i go about this?
This is not the only string i want to perform this operation on, so anything specific to this string (say, checking for 'prasad_hv') will not help.
I tried using split with _
as the delimiter, but it splits prasad
and hv
separately. Please help!
P.S. to generalize, the string would follow the format
string_<digit>-<digit>-<digit>-<digit>-<digit>-<digit>_<String with underscores>_<String>
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.
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("_"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With