views:

130

answers:

4

Hi,

I'm looking for a way to pull the last characters from a String, regardless of size. Lets take these strings into example:

"abcd: efg: 1006746"
"bhddy: nshhf36: 1006754"
"hfquv: nd: 5894254"

As you can see, completely random strings, but they have 7 numbers at the end. How would I be able to take those 7 numbers?

Edit:

I just realized that String[] string = s.split(": "); would work great here, as long as I call string[2] for the numbers and string[1] for anything in the middle.

+12  A: 

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.

Jon Skeet
...I don't know why I didn't think of that. I guess I was just having a slow moment. Thanks for the quick reply, Jon!
PuppyKevin
+1  A: 

This should work

 Integer i= Integer.parseInt(text.substring(text.length() - 7));
Prasoon Saurav
+3  A: 

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.

Chris Dodd
The split part is VERY wrong, but I like the `lastIndexOf` options, so +1. I'll delete this comment after you fix the `split` (look up docs).
polygenelubricants
One serendipitous aspect of the `lastIndexOf` approach is that if there *aren't* any spaces, `lastIndexOf` will return -1, so you'll end up with the whole string (`s.substring(0)`).
Jon Skeet
s.substring(s.lastIndexOf(':') + 1);I would like to use that, but how would I be able to get the letters after the first colon? Wouldn't it be s.indexOf(":", 1)?
PuppyKevin
+3  A: 

I'd use either String.split or a regex:


Using String.split

String[] numberSplit = yourString.split(":") ; 
String numbers = numberSplit[ (numberSplit.length-1) ] ; //!! last array element

Using RegEx (requires import java.util.regex.*)

String numbers = "" ;
Matcher numberMatcher = Pattern.compile("[0-9]{7}").matcher(yourString) ;
    if( matcher.find() ) {
            numbers = matcher.group(0) ;
    } 
FK82
Regex should be `[0-9]{7}$` to make sure it matches the **last** 7 digits.
Willi
@ Willi Schönborn: Agreed. The OP's case suggested that the other groups in the string would always contain letters. I was assuming that it was unnecessary to specify a boundary.
FK82