How to get the desired character from variable-sized strings?

I need to extract the desired line attached to the word.

for example

 pot-1_Sam  
 pot-22_Daniel
 pot_444_Jack
 pot_5434_Bill

I need to get the names from the lines above. Sam, Daniel, Jack and Bill. The fact is that if I use a substring, the position continues to change due to the length of the number. How to use them with REGEX.

Update: Some lines have 2 options for underlining, for example

 pot_US-1_Sam  
 pot_RUS_444_Jack
+4
source share
5 answers

Your Answer:

String[] s = new String[4];
s[0] = "pot-1_Sam";
s[1] = "pot-22_Daniel";
s[2] = "pot_444_Jack";
s[3] = "pot_5434_Bill";
ArrayList<String> result = new ArrayList<String>();
for (String value : s) {
    String[] splitedArray = value.split("_");
    result.add(splitedArray[splitedArray.length-1]);
}

for(String resultingValue : result){
    System.out.println(resultingValue);
}
+3
source

, . , - , lastIndexOf substring.

 String result = yourString.substring(yourString.lastIndexOf("_")+1, yourString.length());
+4

2 :

  • indexOf, _ ( , , , _). _, substring, , .

  • . , , , , , , , , , . , \\d+_ ( , ) split. , , .

+3

"_" . REGEX.

split :

   String[] strArray = strValue.split("_");  
   String lastToken = strArray[strArray.length -1];    
+1
    String[] s = {
        "pot-1_Sam",
        "pot-22_Daniel",
        "pot_444_Jack",
        "pot_5434_Bill"
    };
    for (String e : s)
        System.out.println(e.replaceAll(".*_", ""));
+1

Source: https://habr.com/ru/post/1621596/


All Articles