How to get the last characters in a String in Java, regardless of String size
Lots of things you could do.
s.substring(s.lastIndexOf(':') + 1);
will get everything after the last colon.
s.substring(s.lastIndexOf(' ') + 1);
everything after the last space.
String numbers[] = s.split("[^0-9]+");
splits off all sequences of digits; the last element of the numbers array is probably what you want.
This question is the top Google result for "Java String Right".
Surprisingly, no-one has yet mentioned Apache Commons StringUtils.right():
String numbers = org.apache.commons.lang.StringUtils.right( text, 7 );
This also handles the case where text
is null, where many of the other answers would throw a NullPointerException.
How about:
String numbers = text.substring(text.length() - 7);
That assumes that there are 7 characters at the end, of course. It will throw an exception if you pass it "12345". You could address that this way:
String numbers = text.substring(Math.max(0, text.length() - 7));
or
String numbers = text.length() <= 7 ? text : text.substring(text.length() - 7);
Note that this still isn't doing any validation that the resulting string contains numbers - and it will still throw an exception if text
is null.