2

Can anyone help me to split the string by number Eg: "I Need 5000 points" is the string I want "5000" from that string.

I tried many ways like:

//split the string by RegExp:
String array = string.split(".*\\d.")

I am getting the output but its not what I expect

Output:

 array[0] = ""
 array[1]  ="points

Can anyone help me to find the proper solution?

Elazar
  • 20,415
  • 4
  • 46
  • 67
Satish
  • 537
  • 2
  • 9
  • 21

7 Answers7

5
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher("I Need 5000 points");
while (matcher.find()) {            
    System.out.println(matcher.group());
}
Melih Altıntaş
  • 2,495
  • 1
  • 22
  • 35
2

you want to split on everything that is not a number:

String array[] = string.split("\\D+");
rolfl
  • 17,539
  • 7
  • 42
  • 76
1
        String str="I Need 5000 points";

        Pattern p = Pattern.compile("\\d)");
        Matcher m = p.matcher(str);
        while(m.find())
        {
            System.out.println(m.group());
        }
Prabhakaran Ramaswamy
  • 25,706
  • 10
  • 57
  • 64
1

Try this.

Pattern p=Pattern.compile("\\d+");
    Matcher m=p.matcher(yourString);
    while(m.find()){
    System.out.println(m.group());
}
Aneesh
  • 1,703
  • 3
  • 24
  • 34
1

Could you try this one (should also work with digit numbers):

echo preg_replace("/[^0-9,.]/", "", "I Need 5000 points");
Arjen
  • 289
  • 2
  • 4
  • 11
0

In general you can try to split by
str.matches("-?\\d+(\\.\\d+)?"); //match a number with optional '-' and decimal.

Although this is not the way what you have tried. Get the string[] by myString.split("\\s+"); and then check the splitted string contains any number or not.

Be careful with the above RegEx mechanism, though, as it'll fail if your using non-latin (i.e. 0 to 9) digits. For example, arabic digits.

You can take a look here - How to check if a String is numeric in Java

Community
  • 1
  • 1
Pradip
  • 3,189
  • 3
  • 22
  • 27
-1
import java.util.regex.*;

String myString = "I Need 5000 points";
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(myString);
if(matcher.find())            
    System.out.println(matcher.group(0));
Sheldon Neilson
  • 803
  • 4
  • 8