100

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.

1
  • Both your question and several answers mention String.split(), but it is worth noting that s.split(": ") is going to compile a new java.uitl.regex.Pattern every time you call it, then match your string with that pattern, creating a regex Matcher and an ArrayList before the String[] that is returned. It will be relatively slow and will allocate far more than necessary to solve this problem. Whether this matters depends on the nature of your application. I generally avoid split() unless I really need it. (Note that split() does not use regex if you split on a single character.) Commented Aug 23, 2019 at 7:45

11 Answers 11

166

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Very cool......
115

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.

2 Comments

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)).
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)?
77

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.

2 Comments

I wonder too. This way is much more safe than handling all possible problems.
This is also the only answer that works if you want/need a single expression to safely convert something to a string and get up to the last n characters. For example, you could do StringUtils.right(Objects.toString(someObj), 7).
27

This code works for me perfectly:

String numbers = text.substring(Math.max(0, text.length() - 7));

Comments

9

You can achieve it using this single line code :

String numbers = text.substring(text.length() - 7, text.length());

But be sure to catch Exception if the input string length is less than 7.

You can replace 7 with any number say N, if you want to get last 'N' characters.

1 Comment

It's better to check in advance whether the input length is 7 or longer, and then do the substring.
4

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) ;
    } 

2 Comments

Regex should be [0-9]{7}$ to make sure it matches the last 7 digits.
@ 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.
3
String inputstr = "abcd: efg: 1006746"
int startindex = inputstr.length() - 10;
String outputtendigitstr = inputstr.substring(startindex);

Make sure you check string length is more than 10.

Comments

2
org.apache.commons.lang3.StringUtils.substring(s, -7) 

gives you the answer. It returns the input if it is shorter than 7, and null if s == null. It never throws an exception.

See https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#substring-java.lang.String-int-int-

Comments

1

This should work

 Integer i= Integer.parseInt(text.substring(text.length() - 7));

Comments

1

StringUtils.substringAfterLast("abcd: efg: 1006746", ": ") = "1006746";

As long as the format of the string is fixed you can use substringAfterLast.

Comments

0

E.g : "abcd: efg: 1006746" "bhddy: nshhf36: 1006754" "hfquv: nd: 5894254"

-Step 1: String firstString = "abcd: efg: 1006746";

-Step 2: String lastSevenNumber = firstString.substring(firstString.lastIndexOf(':'), firstString.length()).trim();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.