Satish
Satish

Reputation: 537

Split the String by number

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?

Upvotes: 2

Views: 211

Answers (7)

rolfl
rolfl

Reputation: 17707

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

String array[] = string.split("\\D+");

Upvotes: 2

Sheldon Neilson
Sheldon Neilson

Reputation: 803

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

Upvotes: -1

Pradip
Pradip

Reputation: 3177

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

Upvotes: 0

Prabhakaran Ramaswamy
Prabhakaran Ramaswamy

Reputation: 26094

        String str="I Need 5000 points";

        Pattern p = Pattern.compile("\\d)");
        Matcher m = p.matcher(str);
        while(m.find())
        {
            System.out.println(m.group());
        }

Upvotes: 1

Arjen
Arjen

Reputation: 309

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

echo preg_replace("/[^0-9,.]/", "", "I Need 5000 points");

Upvotes: 1

Aneesh
Aneesh

Reputation: 1733

Try this.

Pattern p=Pattern.compile("\\d+");
    Matcher m=p.matcher(yourString);
    while(m.find()){
    System.out.println(m.group());
}

Upvotes: 1

Melih Altıntaş
Melih Altıntaş

Reputation: 2535

Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher("I Need 5000 points");
while (matcher.find()) {            
    System.out.println(matcher.group());
}

Upvotes: 5

Related Questions