简体   繁体   中英

Extract all numbers in string to array

I have a string like this

+3.15% price per day(+63.00% price at day 20)

and I want to be able to export it into an array so it becomes something like this

{3.15 , 63.00, 20}

Can someone help me with this? I'm really stuck at this right now, as I'm not 100% sure how to approach it :\\ The reason why I want to do this is because I want to multiple the numbers inside that string by a number like 4, so the result will become

+12.60% price per day(+252.00% price at day 20)

Here are all the possible cases

-3.15% price per day(-63.00% price at day 20)

=>  -12.60% price per day(-252.00% price at day 20)

+0.76 price per day(+15.20 price at day 20)

=>  +3.04 price per day(+60.80 price at day 20)
// export numbers
string input = "+3% price per day(+60% price at day 20)";
int[] array = Regex.Matches(input, @"\d+").OfType<Match>().Select(e => int.Parse(e.Value)).ToArray();

// replace numbers
double k = 3;
string replaced = Regex.Replace(input, @"\d+", e => (int.Parse(e.Value) * k).ToString());

// replace only percents
k = 4;
string replacedPercents = Regex.Replace(input, @"(\d+)%", e => (int.Parse(e.Groups[1].Value) * k).ToString() + "%");

// floating conversion
input = "+0.87 price per day(+63.00 price at day 20)";
string replacedFloating = Regex.Replace(input, @"\+(\d+\.(\d+)|\d+)", e => "+" + (double.Parse(e.Groups[1].Value, CultureInfo.InvariantCulture) * k).ToString(e.Groups[2].Length == 0 ? "0" : "0." + new string('0', e.Groups[2].Length), CultureInfo.InvariantCulture));

// floating conversion with negatives
input = "-0.87 price per day(+63.00 price at day 20)";
string replacedFloatingNegative = Regex.Replace(input, @"([+-])(\d+\.(\d+)|\d+)", e => e.Groups[1].Value + (double.Parse(e.Groups[2].Value, CultureInfo.InvariantCulture) * k).ToString(e.Groups[3].Length == 0 ? "0" : "0." + new string('0', e.Groups[3].Length), CultureInfo.InvariantCulture));

replaced is

+9% price per day(+180% price at day 60)

replacedPercents is

+12% price per day(+240% price at day 20)

replacedFloating is

+12.60 price per day(+252.00 price at day 20)

replacedFloatingNegative is

-3.48 price per day(+252.00 price at day 20)
char[] test = new Char[10];
        string val = "+3% price per day(+60% price at day 20)";
        try
        {
            for (int i = 0, j = 0; val[i] != null ; i++)
            {
                if (Char.IsDigit(val[i]))
                {
                    test[j++] = val[i];
                    Console.WriteLine(val[i]);
                }

            }
        }
        catch (Exception){ }

Use test array as per your need

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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