2012-08-28 112 views
0

我有字符串,而且我需要從它們中精選雙精度值。他們都是格式:提取數字並從字符串中提取一個雙精度值

"Blabla 11/moreBla 17-18" That should become 11.1718 
"Blabla 7/moreBla 8-9" --> 7.89 
"Blabla 4/moreBla 6-8" --> 4.68 

還可以有多餘的空格或破折號可能是一個正斜槓。所以,類似的東西:

"Blabla 11/moreBla 17-18" 
"Blabla 11/moreBla 17-18" 
"Blabla 11/moreBla 17/18" 
"Blabla 11/moreBla 17/18" 
"Blabla 11/moreBla 17/18" 

我試着先拆分字符串,但顯然有所有這些其他情況。所以拆分在這裏運行得不好。 RegEx可能有幫助嗎?

回答

0

代碼:

using System; 
using System.Text.RegularExpressions; 

class Program 
{ 
    static void Main() 
    { 
     string input = "Blabla 11/moreBla 17-18"; 
     string[] s = input.Split('/'); 
     Console.WriteLine(Regex.Replace(s[0], @"[^\d]", "") + "." + Regex.Replace(s[1], @"[^\d]", "")); 
    } 
} 

輸出:

11.1718 

測試此代碼here


或者驗證碼:

using System; 
using System.Text.RegularExpressions; 

class Program 
{ 
    static void Main() 
    { 
     string input = "Blabla 11/moreBla 17-18"; 
     string[] s = Regex.Replace(input, @"[^\d\/]", "").Split('/'); 
     Console.WriteLine(s[0] + "." + s[1]); 
    } 
} 

輸出:

11.1718 

測試此代碼here

+0

謝謝。替換的例子就是我最終要做的。 – Dimskiy

0

嘗試此

(\d+).+?(\d+).+?(\d+) 

\1.\2\3 

替換它基本上它匹配的數字的第一組,並把它的整數部分,然後將其相匹配的第二和第三組數字,不管它們之間是什麼,並且做出小數部分。

C#代碼將

public double MatchNumber(string input){ 
    Regex r = new Regex(@"(\d+).+?(\d+).+?(\d+)"); 
    Match match = r.Match(input); 
    if (match.Success){ 
     return Convert.toDouble(
      match.Groups[1].Value+"."+ 
      match.Groups[2].Value+ 
      match.Groups[2].Value); 
    } 
    else{ 
     return null; 
    } 
} 
0

你可以嘗試這樣的

String data = "Blabla 11/moreBla 17-18"; 
data = Regex.Replace(DATA, "[a-zA-Z ]", ""); 

data = String.Concat(DATA.Split('/')[0], "." , Regex.Replace(DATA.Split('/')[1], "(?:[^a-z0-9 ]|(?<=['\"])s)","")); 

double MyValue = Convert.ToDouble(data); 

希望這將幫助一些事情。

2

根據你在你的問題給了測試用例:

string input = @"Blabla 11/moreBla 17/18"; 

MatchCollection matches = Regex.Matches(input, "(\\d+)"); 
double val = Convert.ToDouble(matches[0].Value + "." + matches[1].Value + matches[2].Value);