Home > DeveloperSection > Forums > how to check wheather a string has a word followed by a number or not
zack mathews
zack mathews

Total Post:23

Posted on    December-10-2015 4:40 AM

 Java Java  Regex  String 

 1 Reply(s)
 449  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?

Mayank Tripathi
Mayank Tripathi

Total Post:397

Posted on    December-10-2015 4:53 AM

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

Don't want to miss updates? Please click the below button!

Follow MindStick