2012-04-19 65 views
1

Float值我有以下類型的字符串列表:得到字符串

 
27 km 
56.1 km 
45 KM 
96.2km 
87 k 

而且我想對每一個數值。正如你可以看到它們中的一些是浮點值,並且後綴「km」有時錯誤輸入。我在尋找的輸出如下:在網絡上

 
27 
56.1 
45 
96.2 
87 

我發現正則表達式是字符串轉換爲數字,但他們沒有考慮到某些值可以是浮動的,我怎麼能寫一個函數或找到滿足我的要求的表達式?

+0

你嘗試過'floatval()'嗎? – Blake 2012-04-19 16:29:22

+0

事實上,我需要的,你應該發表你的評論作爲答案 – 2012-04-19 16:43:11

+0

你已經選擇了答案。沒什麼大不了的,除非你打算改用我的。哈。 – Blake 2012-04-19 16:47:37

回答

3

$var = floatval($float);是你在找什麼。

0

對於這些字符串,可以使用/^\d+(\.\d+)?/

0

浮點正則表達式:?? [ - +] [0-9] * \ [0-9] +

2

只是parseFloat()他們。 parseFloat()將以數字開頭的字符串轉換爲數字並停止使用第一個非數字字符。

parseFloat('96.2 km') = 96.2

+1

這是JavaScript。 – jeremyharris 2012-04-19 16:31:02

+0

你說得對。 'floatval()'是php的等價物。一整天都在處理Javascript! – 2012-04-19 16:31:59

+0

我經常做同樣的事情:) – jeremyharris 2012-04-19 16:34:12

4

無需正則表達式,只需使用floatval

$float = floatval($string); 
0

嘗試。對我的作品

try {  
    Regex regexObj = new Regex(@"\b\d+(?:\.\d{0,}|)");  
    Match matchResults = regexObj.Match(subjectString);  
    while (matchResults.Success) {  
     // matched text: matchResults.Value  
     // match start: matchResults.Index  
     // match length: matchResults.Length  
     matchResults = matchResults.NextMatch();  
    }  
} catch (ArgumentException ex) {  
    // Syntax error in the regular expression  
} 

PHP方式

preg_match_all('/\b\d+(?:\.\d{0,}|)/', $subject, $result, PREG_PATTERN_ORDER); 
for ($i = 0; $i < count($result[0]); $i++) { 
    # Matched text = $result[0][$i]; 
}