---
title: "how to check wheather a string has a word followed by a number or not"  
description: "how to check wheather a string has a word followed by a number or not"  
author: "zack mathews"  
published: 2015-12-10  
updated: 2015-12-10  
canonical: https://www.mindstick.com/forum/33711/how-to-check-wheather-a-string-has-a-word-followed-by-a-number-or-not  
category: "java"  
tags: ["java", "regex", "string"]  
reading_time: 2 minutes  

---

# how to check wheather a string has a word followed by a number or not

I have a [string](https://www.mindstick.com/articles/1527/string-split-in-c-sharp) like\

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

Is there a way to [check if](https://www.mindstick.com/forum/12878/how-to-check-if-an-asp-dot-net-file-upload-control-has-a-file-in-jquery) the [word](https://www.mindstick.com/forum/305/read-word-file) "top" has a number following it. [If yes](https://www.mindstick.com/forum/159589/can-we-crash-jvm-if-yes-then-how) get that number to another string.\
I'm [thinking](https://www.mindstick.com/blog/11889/how-to-change-your-thinking-paradigm) to use indexOf("top") and [add](https://www.mindstick.com/forum/12983/add-address-in-textbox-when-page-is-load-and-if-i-search-address-in-textbox-show-in-map-by-javascript) 4 to that and try to get the next word. Not sure how it will work. Any [suggestions](https://www.mindstick.com/blog/299486/how-to-write-for-your-audience)?

## Replies

### Reply by Anonymous User

Regex can help us [check](https://yourviews.mindstick.com/story/2248/never-forget-to-check-these-specifications-before-buying-a-mobile-phone) 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));}
```


---

Original Source: https://www.mindstick.com/forum/33711/how-to-check-wheather-a-string-has-a-word-followed-by-a-number-or-not

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
