-1

I receive a formatted string and I can't change the source ; it look something like this :

{
"value": 4.12
}

I have to parse it into a double to show only the number. I get I should clean it with a regex before using double.TryParse(), but I have no idea how to format the regex...

Saryk
  • 345
  • 1
  • 12

4 Answers4

2

if you only missed a double-quotes around the value, that is a valid JSON. You can parse it using almost any json library.

Leonardo
  • 10,737
  • 10
  • 62
  • 155
2

With LINQ to JSON you may retrieve the value in one line:

var json = @"{
    ""value"" : 4.12
}";
var value = (double)JObject.Parse(json)["value"];

Demo: https://dotnetfiddle.net/e0viPY

P.S.

Since Json.NET accepts more relaxed syntax, this code would work even with the original question edition (i.e. unquoted key):

var json = "{ value : 4.12 }";
var value = (double)JObject.Parse(json)["value"];

Demo: https://dotnetfiddle.net/iLERPb

Dmitry Egorov
  • 9,542
  • 3
  • 22
  • 40
0

you can use below regex -

[0-9]+(.[0-9][0-9]?)?

0

Quick and dirty regular expression soluition:

  string source = @"{
     ""value"": 4.12
  }";

  double result = double.Parse(Regex.Match(source, @"-?[0-9]*\.?[0-9]+").Value,
    CultureInfo.InvariantCulture);

A better implementation, however, is to decerialize it as JSON

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215