Dimskiy
Dimskiy

Reputation: 5301

Extract numbers and make a double from a string

I have strings and I need to make doubles from them. They're all in format:

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

etc.

There could also be extra spaces or dash could be a forward slash. So, anything like that:

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

I tried splitting the string first, but then apparently there are all these other cases. So split isn't working well here. Maybe RegEx could be of help?

Upvotes: 0

Views: 70

Answers (4)

Gabber
Gabber

Reputation: 5452

Try this

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

replace it with

\1.\2\3

Basically it matches the first group of digits and put it to the integer part, then it matches the second and the third group of digits, no matter what is between them, and makes the decimal part.

The c# code would be

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

Upvotes: 0

Ωmega
Ωmega

Reputation: 43673

Code:

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]", "")); 
    }
}

Output:

11.1718

Test this code here.


Or this code:

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

Output:

11.1718

Test this code here.

Upvotes: 0

coolmine
coolmine

Reputation: 4463

Based on the test cases you gave in your question:

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

Upvotes: 2

Kundan Singh Chouhan
Kundan Singh Chouhan

Reputation: 14282

You could try some thing like this

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

Hope this will help.

Upvotes: 0

Related Questions