提取数字并从字符串中提取一个双精度值

问题描述:

我有字符串,而且我需要从它们中精选双精度值。他们都是格式:提取数字并从字符串中提取一个双精度值

"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可能有帮助吗?

代码:

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

尝试此

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

你可以尝试这样的

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

希望这将帮助一些事情。

根据你在你的问题给了测试用例:

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