Splitting a String in Java with underscore as delimiter

后端 未结 7 1012
野的像风
野的像风 2021-01-13 00:49

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

相关标签:
7条回答
  • 2021-01-13 01:09

    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");
    
    0 讨论(0)
  • 2021-01-13 01:12

    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.
    
    0 讨论(0)
  • 2021-01-13 01:14

    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.

    0 讨论(0)
  • 2021-01-13 01:18

    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("_"));
    
    0 讨论(0)
  • 2021-01-13 01:23

    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);
        }
    }
    
    0 讨论(0)
  • 2021-01-13 01:27

    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

    0 讨论(0)
提交回复
热议问题