4

I need to extract the desired string which 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 above strings. i.e Sam, Daniel, Jack and Bill. Thing is if I use substring the position keeps on changing due to the length of the number. How to achieve them using REGEX.

Update: Some strings has 2 underscore options like

 pot_US-1_Sam  
 pot_RUS_444_Jack
Dinesh Ravi
  • 1,209
  • 1
  • 17
  • 35

5 Answers5

4

Assuming you have a standard set of above formats, It seems you need not to have any regex, you can try using lastIndexOf and substring methods.

 String result = yourString.substring(yourString.lastIndexOf("_")+1, yourString.length());
ParkerHalo
  • 4,341
  • 9
  • 29
  • 51
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
3

You have 2 options:

  1. Keep using the indexOf method to get the index of the last _ (This assumes that there is no _ in the names you are after). Once that you have the last index of the _ character, you can use the substring method to get the bit you are after.

  2. Use a regular expression. The strings you have shown essentially have the pattern where in you have numbers, followed by an underscore which is in turn followed by the word you are after. You can use a regular expression such as \\d+_ (which will match one or more digits followed by an underscore) in combination with the split method. The string you are after will be in the last array position.

npinti
  • 51,780
  • 5
  • 72
  • 96
3

Your answer is:

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);
}
Rajnikant Patel
  • 561
  • 3
  • 19
1

Use a string tokenizer based on '_' and get the last element. No need for REGEX.

Or use the split method on the string object like so :

   String[] strArray = strValue.split("_");  
   String lastToken = strArray[strArray.length -1];    
Oliver Watkins
  • 12,575
  • 33
  • 119
  • 225
1
    String[] s = {
        "pot-1_Sam",
        "pot-22_Daniel",
        "pot_444_Jack",
        "pot_5434_Bill"
    };
    for (String e : s)
        System.out.println(e.replaceAll(".*_", ""));