2016-02-12 103 views
2

java中用於從文本中提取數字並解析它的最佳實踐是什麼?解析(轉換)包含數字的字符串數字類型

例如:

String s = "Availability in 20 days"; 

請不要只是堅持我在尋找一個好的一般的做法和情景的例子。

謝謝。

+0

如果輸入的是 「號碼134來第二次」,那麼你要輸出什麼? – Hackerdarshi

+0

我在想這可能是一個數字集合。但我寧願忽略數字與文字棍子 – kidwon

+0

@kidwon請繼續並接受答案。或者如果您能夠想出一些可以幫助社區的最佳做法,請輸入您自己的答案並接受它。 –

回答

1

使用正則表達式:

Pattern p = Pattern.compile("-?\\d+"); 
Matcher m = p.matcher("Availability in 20 days"); 
while (m.find()) { 
    int number = Integer.parseInt(m.group()); 
    ... 
} 
1

怎麼樣的正則表達式+的replaceAll?

代碼:

String after = str.replaceAll("\\D+", ""); 
+0

它必須是'「\\ D +」'。 – saka1029

+0

謝謝我修好了。奇怪,昨天它看起來像2斜線......但.. –

1

我不清楚自己想做的事,但這裏有一些解決方案,可以幫助你:

  1. 列表項目使用.indexOf和.substring找到號碼字符串

    • 例如:

      String s; 
      String str = new String("1 sentence containing 5 words and 3 numbers."); 
      ArrayList<Integer> integers = new ArrayList<Integer>(); 
      for (int i = 0; i <= 9; i++) { 
          int start = 0; 
          while (start != -1) { 
           String sub = str.substring(start); 
           int x = sub.indexOf(i); 
           if (x != -1) { 
            s = sub.substring(x, x+1); 
            integers.add(Integer.parseInt(s)); 
            start = x; 
           } else { 
            //number not found 
            start = -1; 
           } 
          } 
      } 
      
  2. 一次提取一個字符並嘗試解析它,如果沒有例外,它是一個數字。我肯定不建議這個解決方案,但它也應該工作。不幸的是,我不能告訴你哪種方法更快,但我可以想象 - 儘管命令較少 - 第二個版本更慢,考慮到有幾個例外拋出。

    String s; 
    int integ; 
    ArrayList<Integer> integers = new ArrayList<Integer>(); 
    String str = new String("1 sentence containing 5 words and 3 numbers."); 
    for (int i = 0; i < str.length(); i++) { 
        s = str.substring(i,i+1); 
        try { 
         integ = Integer.parseInt(s); 
         integers.add(integ); 
        } catch (NumberFormatException nfe) { 
         //nothing 
        } 
    } 
    
0

如果有serveral的數字則

String[] after = str.replaceAll("\\D+", " ").split("\\s+");