2

This is continuation of How to get the desired character from the variable sized strings? but includes additional scenarios from which, a person names are to be extracted

 pot-1_Sam  [Sam is the word to be extracted]
 pot_444_Jack [Jack is the word to be extracted]
 pot_US-1_Sam  [Sam is the word to be extracted]
 pot_RUS_444_Jack[Jack is the word to be extracted]
 pot_UK_3_Nick_Samuel[Nick_Samuel is the word to be extracted]
 pot_8_James_Baldwin[James_Baldwin is the word to be extracted]
 pot_8_Jack_Furleng_Derik[Jack_Furleng_Derik is the word to be extracted]

Above are the Sample words from which the names person names are to be extracted. One thing to note is that The person name will always start after a "Number" and an "Underscore". How to achieve the above using Java?

Community
  • 1
  • 1
Dinesh Ravi
  • 1,209
  • 1
  • 17
  • 35

5 Answers5

2

Use the following regular expression:

^.*\d+_(.*)$

... and extract the value of the 1st group.

Jason
  • 11,744
  • 3
  • 42
  • 46
2
String[] strings = {
        "pot-1_Sam",
        "pot_444_Jack",
        "pot_US-1_Sam",
        "pot_RUS_444_Jack",
        "pot_UK_3_Nick_Samuel",
        "pot_8_James_Baldwin",
        "pot_8_Jack_Furleng_Derik"
};

Pattern pattern = Pattern.compile("\\d_(\\w+)$");
for (String s : strings ){
    Matcher matcher = pattern.matcher(s);
    if (matcher.find()) {
        System.out.println(matcher.group(1));
    }
}
John E.
  • 418
  • 2
  • 10
1

Here is the regex: \d_(.*$)

\d stands for one digit

_ stands for underscore

() stands for group

.*$ stands for "all till the end of line"

sguan
  • 1,039
  • 10
  • 26
1
    String str= "pot_8_Jack_Furleng_Derik";
     // name starts after number and _
    Pattern p = Pattern.compile("\\d+_");
    Matcher m = p.matcher(str);

    int index = -1;
    // find the index of name
    if(m.find())
    index =  m.start()+2;

    str=  str.substring(index);
    System.out.print(str);
Ramanlfc
  • 8,283
  • 1
  • 18
  • 24
0

You can try using Reflection to get the actual name of the variable as seen here You can further break that down with Regex, as also mentioned

Community
  • 1
  • 1