【问题标题】:Most efficient way to extract all the (natural) numbers from a string从字符串中提取所有(自然)数字的最有效方法
【发布时间】:2010-01-30 21:09:23
【问题描述】:

用户可能希望根据需要分隔数字。

从字符串中提取所有(自然)数字的最有效(或简单的标准函数)是什么?

【问题讨论】:

  • 请注意,“自然数”的定义不明确(参见en.wikipedia.org/wiki/Natural_number)。此外,您希望允许的数字大小是否有任何最大限​​制,或者它们可以是任何大小?

标签: java string numbers extract


【解决方案1】:

您可以使用正则表达式。我从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());
       }
    }
}

它找到每个数字的开始和结束索引。正则表达式 \d+ 允许以 0 开头的数字,但如果您愿意,可以轻松更改。

【讨论】:

    【解决方案2】:

    我不确定我是否完全理解您的问题。但是,如果您只想提取所有非负整数,那么这应该可以很好地工作:

    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"]
    

    然后将字符串解析为整数(如果需要)。

    【讨论】:

      【解决方案3】:

      如果你知道分隔符,那么:

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

      如果不这样做,您可能需要进行预处理 - 您可以执行 x.replace("[A-Za-z]", " "); 并将所有字符替换为空格并使用空格作为分隔符。

      希望有所帮助 - 我认为没有内置函数。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-07
        • 1970-01-01
        • 2016-06-24
        • 1970-01-01
        • 2015-11-11
        • 1970-01-01
        相关资源
        最近更新 更多