Jeeppp
Jeeppp

Reputation: 1573

Check if a string has a word followed by a number

I have strings like:

    String test="top 10 products";
    String test2="show top 10 products";

Is there a way to check if the word "top" has a number following it? If so, how to get that number to another string?

I'm thinking about using indexOf("top") and add 4 to that and try to get the next word. Not sure how it will work. Any suggestions?

Upvotes: 0

Views: 473

Answers (2)

Jiri Tousek
Jiri Tousek

Reputation: 12440

If you only want to extract a possible number after single / first occurrence of "top", that's a viable way. Don't forget to check for existence of the word, and that there's something behind it at all.

You can also use regular expression for this, which will need a bit less error checking:

top\\s+([0-9]+)

You could even make a Pattern out of this, and then iterate the Matcher.find() method and extract the numbers for multiple matches:

Pattern pat = Pattern.compile("top\\s+([0-9]+)");
Matcher matcher = pat.matcher("top 10 products or top 20 products");
while (matcher.find()) {
    System.out.println(matcher.group(1));
}

Upvotes: 1

TheLostMind
TheLostMind

Reputation: 36304

An evil regex can help you.

    String test="top 10 products";
    System.out.println(test.replaceAll(".*?\\w+\\s+(\\d+).*", "$1"));

O/P :

10

Note : This will return the entire String in case there is no "Word[space]digits" in the String. You will have to do a length check for the actual String and the returned String. If the length is same, then your String doesn't contain the expected pattern.

Upvotes: 0

Related Questions