Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a String in Java with underscore as delimiter

Tags:

java

string

split

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>
like image 364
Bharath Naidu Avatar asked Oct 18 '12 06:10

Bharath Naidu


2 Answers

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.
like image 51
Juvanis Avatar answered Nov 15 '22 12:11

Juvanis


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("_"));
like image 25
Reddy Avatar answered Nov 15 '22 12:11

Reddy