1

I have a string in java like:

 "Corrected Acceleration 20130816_053116_RCS2_21 GNS Science"

I am looking to get the last part of the number sequence. It is the number after the last underscore.

In this case:

21

More examples are

 "Corrected Acceleration 20130346_053116_RCS2_15 GNS Science"

Want 15

 "Corrected Acceleration 20130346_053116_RCS2_13 GNS Science"

Want 13

 "Acceleration 123214_05312323_RCS2_40 GNS Science"

Want 40

This format will stay the same. The variations will be different numbers and possibly the front substring Corrected might be missing.

How would I go about extracting this?

enjoylife
  • 3,801
  • 1
  • 24
  • 33
  • possible duplicate of [How to split a String in Java](http://stackoverflow.com/questions/3481828/how-to-split-a-string-in-java) – Colin D Mar 03 '14 at 20:38
  • 3
    Have you attempted to write a regex? – joemfb Mar 03 '14 at 20:39
  • What *total output* do you want? What if there are *two* such numbers in the input? – user2864740 Mar 03 '14 at 20:39
  • You might need to define the format a bit better, is the format "a name consisting of multiple words and spaces, then a number with underscores..." or is it a "word space word space, then a number with underscores..." is just one potential problem. – NESPowerGlove Mar 03 '14 at 20:41
  • Can you provide a few more sample strings so we can get an idea of what will vary and what will stay the same? – Mar Mar 03 '14 at 20:53

2 Answers2

1

This SHOULD get what you need. Please bear in mind i have not tested thism but the logic should work:

String test = "Corrected Acceleration 20130816_053116_RCS2_21 GNS Science";
int lastUnderScore = test.lastIndexOf("_");
test = test.substring(lastUnderScore + 1);
int numLength = test.indexOf(" ");
int number = Integer.valueOf(test.substring(0, numLength));
  1. Find the last instance of '_'
  2. cut string back to start at the beginning of the number
  3. find the position of the first ' ' (This will now be after the number you need)
  4. cut string down to before the space and cast to an integer.
Lex Webb
  • 2,772
  • 2
  • 21
  • 36
1

You can use a regex like this:

Pattern pattern = Pattern.compile("_[0-9]+ ");
Matcher matcher = pattern.matcher(text);
matcher.find();

// Note the + 1 and - 1 here to get rid of the leading underscore and the trailing space
int number = Integer.parseInt(text.subString(matcher.start() + 1, matcher.end() - 1));
quazzieclodo
  • 831
  • 4
  • 10