Most efficient way to extract all the (natural) numbers from a string

☆樱花仙子☆ 提交于 2019-12-23 10:41:28

问题


Users may want to delimit numbers as they want.

What is the most efficient (or a simple standard function) to extract all the (natural) numbers from a string?


回答1:


You could use a regular expression. I modified this example from Sun's regex matcher tutorial:

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class Test {

    private static final String REGEX = "\\d+";
    private static final String INPUT = "dog dog 1342 dog doggie 2321 dogg";

    public static void main(String[] args) {
       Pattern p = Pattern.compile(REGEX);
       Matcher m = p.matcher(INPUT); // get a matcher object
       while(m.find()) {
           System.out.println("start(): "+m.start());
           System.out.println("end(): "+m.end());
       }
    }
}

It finds the start and end indexes of each number. Numbers starting with 0 are allowed with the regular expression \d+, but you could easily change that if you want to.




回答2:


I'm not sure I understand your question exactly. But if all you want is to pull out all non-negative integers then this should work pretty nicely:

String foo = "12,34,56.0567 junk 6745 some - stuff tab tab 789";
String[] nums = foo.split("\\D+");

// nums = ["12", "34", "56", "0567", "6745", "789"]

and then parse out the strings as ints (if needed).




回答3:


If you know the delimiter, then:

String X = "12,34,56";
String[] y = X.split(","); // d=delimiter
int[] z = new int[y.length];
for (int i = 0; i < y.length; i++ )
{
    z[i] = java.lang.Integer.valueOf(y[i]).intValue();
}

If you don't, you probably need to pre-process - you could do x.replace("[A-Za-z]", " "); and replace all characters with spaces and use space as the delimiter.

Hope that helps - I don't think there is a built-in function.



来源:https://stackoverflow.com/questions/2169437/most-efficient-way-to-extract-all-the-natural-numbers-from-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!