简体   繁体   English

从字符串C#中提取双精度值

[英]Extracting double value from a string c#

I want to extract the double from my string. 我想从字符串中提取双精度。

buff = "VA VV_CELL1 3.55"

When i use the following code 当我使用以下代码

private void GetLine(string msg, string buff, double numb)
{
    comPort.WriteLine(msg); 
    Thread.Sleep(50);
    buff = comPort.ReadExisting();
    Thread.Sleep(50);
    MatchCollection matches = Regex.Matches(buff, @".*?([-]{0,1} *\d+.\d+)");
    List<double> doubles = new List<double>();
    foreach (Match match in matches)
    {
        string value = match.Groups[1].Value;
        value = value.Replace(" ", "");
        doubles.Add(double.Parse(value));
        Thread.Sleep(200);
        numb = doubles[0];                
    } 
}

This code work for my other strings but "CELL1" contains a number so i dont get the wanted value "3.55" any ideas? 该代码适用于我的其他字符串,但“ CELL1”包含一个数字,因此我无法获得所需的值“ 3.55”吗?

Why you don't simply split this string and take the last part? 为什么不简单地拆分此字符串并占用最后一部分呢?

string numberPart = buff.Split().Last();
double num;
bool validNum = double.TryParse(numberPart, NumberStyles.Any, CultureInfo.InvariantCulture, out num);

Another way is to use Substring and LastIndexOf (which fails if there is no space): 另一种方法是使用SubstringLastIndexOf (如果没有空间,则失败):

string numberPart = buff.Substring(buff.LastIndexOf(' ')).Trim();

To help on your comment : 为了帮助您发表评论

I'd use a method that returns a double? 我会使用返回double?精度值的方法double? (double that can be null): (可以为null的double):

double? GetNumber(string buff)
{
    string numberPart = buff.Split().Last();
    double num;
    bool validNum = double.TryParse(numberPart, NumberStyles.Any, CultureInfo.InvariantCulture, out num);
    if (validNum)
        return num;
    else
        return null;
}

Now you can use the method and you even know whether the number could be parsed successfully or not: 现在,您可以使用该方法,甚至可以知道是否可以成功解析该数字:

double? result = GetNumber("VA VV_CELL1");
bool wasValid = result.HasValue;
if(wasValid)
{
   double value = result.Value;
}

试试这个正则表达式: \\s+\\d+(.)?\\d+

I assume you want to capture both doubles and integers, otherwise you could write \\d+\\.\\d+ . 我假设您想同时捕获双精度数和整数,否则可以编写\\d+\\.\\d+ This : 这个 :

Regex.Matches("VA VV_CELL1 3.55",@"\d+\.\d+")[0]

Returns 3.55 but can't capture 355. 返回3.55,但无法捕获355。

You can capture an integer or decimal preceded by whitespace with \\s+\\d+(\\.\\d+)? 您可以使用\\s+\\d+(\\.\\d+)?捕获带空格的整数或十进制\\s+\\d+(\\.\\d+)? .

Regex.Matches("VA VV_CELL1 3.55",@"\s+\d+(\.\d+)?")[0]

Returns 3.55 while 在返回3.55的同时

Regex.Matches("VA VV_CELL1 355",@"\s+\d+(\.\d+)?")[0]

Returns 355 返回355

If you want to capture only the last field you can use \\s+\\d+(\\.\\d+)?$ ,eg: 如果只想捕获最后一个字段,则可以使用\\s+\\d+(\\.\\d+)?$ ,例如:

Regex.Matches("VA VV_CELL1 3.54 3.55",@"\s+\d+(\.\d+)?$")[0]

Returns 3.55 返回3.55

You don't need to trim whitespace because double.Parse ignores it. 您不需要修剪空格,因为double.Parse忽略它。 You can change the pattern to capture the number in a separate group though, by surrounding the digits with parentheses : 您可以通过以下方式更改模式以将数字捕获到单独的组中:用括号将数字括起来:

Regex.Matches("VA VV_CELL1 3.54 3.55",@"\s+(\d+(\.\d+)?)$")[0].Groups[1]

You need to use Groups[1] because the first group always returns the entire capture 您需要使用Groups[1]因为第一个组始终返回整个捕获

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM