2015-10-19 26 views
-3

我有我需要刪除尾隨字符的字符串。有幾種類型,下面是一些例子:Java子串只保留數字和十進制

「82.882英尺」 「101in」 「15.993ft³」 「10.221毫米」

等。我需要刪除長度分隔符,所以我會留下用繩子:

「82.882」 「101」 「15.993」 「10.221」

想法?

+15

我有一個想法:寫代碼。 – Maroun

+0

我沒有看到一個乾淨的方式來做這個與substring函數。 – ergonaut

+0

1.找到不是數字一部分的第一個字符的索引(只有您可以準確知道數字中允許使用哪些字符)2.將子字符串截至該點 – DJClayworth

回答

1

嘗試使用的字符串的replaceAll,指定沒有小數點或數字的所有字符:

myString = myString.replaceAll("[^0-9\\.]",""); 

「^ 0-9 \」。意味着所有不是數字0到9的字符或小數。之所以我們放兩條斜線是爲了避開這段時間,因爲它在Java正則表達式中的含義與字面字符'。'不同。

+0

轉義'.'裏面的字符類實際上是沒有必要的 –

0

只需使用正則表達式:

String result = input.replaceAll("[^0-9.]", ""); 
0

正則表達式可能適用於此目的。

Pattern lp = Pattern.compile("([\\d.]+)(.*)"); 

    // Optional cleanup using Apache Commons StringUtils 
    currentInput = StringUtils.upperCase(
      StringUtils.deleteWhitespace(currentInput)); 

    Matcher lpm = lp.matcher(currentInput); 
    if(lpm.matches()) 
    { 
     // Values 
     String value = lpm.group(1); 

     // And the trailing chars for further processing 
     String measure = lpm.group(2); 
    } 
相關問題