how to check wheather a string has a word followed by a number or not

Total Post:23

Java  Regex  String 
 781  View(s)
Rate this:
I have a string 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 yes get that number to another string.

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

    Re: how to check wheather a string has a word followed by a number or not

    Regex can help us check it:

    String test="top 10 products";
        System.out.println(test.replaceAll(".*?\\w+\\s+(\\d+).*", "$1"));
    But,  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.

    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:

    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()) {