سؤال

I've seen many people do similar to this in order to get the last word of a String:

 String test =  "This is a sentence";
 String lastWord = test.substring(test.lastIndexOf(" ")+1);

I would like to do similar but get the last few words after the last int, it can't be hard coded as the number could be anything and the amount of words after the last int could also be unlimited. I'm wondering whether there is a simple way to do this as I want to avoid using Patterns and Matchers again due to using them earlier on in this method to receive a similar effect.

Thanks in advance.

هل كانت مفيدة؟

المحلول

I would like to get the last few words after the last int.... as the number could be anything and the amount of words after the last int could also be unlimited.

Here's a possible suggestion. Using Array#split

String str =  "This is 1 and 2 and 3 some more words .... foo bar baz";
String[] parts = str.split("\\d+(?!.*\\d)\\s+");

And now parts[1] holds all words after the last number in the string.

some more words .... foo bar baz

نصائح أخرى

What about this one:

String test = "a string with a large number 1312398741 and some words";
String[] parts = test.split();
for (int i = 1; i < parts.length; i++)
{
    try
    {
        Integer.parseInt(parts[i])       
    }
    catch (Exception e)
    {
        // this part is not a number, so lets go on...
        continue;
    }

    // when parsing succeeds, the number was reached and continue has
    // not been called. Everything behind 'i' is what you are looking for

    // DO YOUR STUFF with parts[i+1] to parts[parts.length] here

}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top