HOW TO CHECK WHEATHER A STRING HAS A WORD FOLLOWED BY A NUMBER OR NOT

zack mathews

Total Post:23

Points:161
Posted by  zack mathews
Java  Regex  String 
 460  View(s)
Ratings:
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. Mayank Tripathi

    Post:397

    Points:3117
    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:

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

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!