-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...

6
  • 1
    if source is a JSON string, deserialize it to obtain property value Commented May 2, 2017 at 14:29
  • 2
    aren't you missing a double quote around the value? Commented May 2, 2017 at 14:30
  • 1
    If you want to learn regular expressions, the resources on the internet for doing so would literally reach to the moon and back. Commented May 2, 2017 at 14:31
  • quick and dirty: double result = double.Parse(Regex.Match(source, @"[0-9]*\.?[0-9]+").Value); Commented May 2, 2017 at 14:31
  • @Leonardo yes indeed, I edited the question Commented May 2, 2017 at 14:33

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Doesn't look like valid JSON to me, although I didn't downvote you
@KSib i think he missed the double-quotes only... common typo...
Looks like you were correct. I upvoted you as well to counter that downvote. Cheers.
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

Comments

0

you can use below regex -

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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.