Find and replace numbers in a string using regex

What I'm trying to achieve is to replace the numbers in the string with the new values ​​computed from (match * int).

So the line input looks like this:

500g Flour
14g Salt
7g Dry yeast
45ml Olive oil
309ml Water

And the result should look like this:

1000g Flour
28g Salt
14g Dry yeast
90ml Olive oil
618 ml Water

row["ingredients"]is DataRow.

This is where I am located:

System.Text.RegularExpressions.
        Regex.Replace(row["ingredients"].ToString(), 
                      @"[^/d]", Delegate(Match match) { return match * 2; },
                      RegexOptions.Multiline);

Any solution is welcome.

+5
source share
4 answers

The first problem is that your regular expression matches only characters that are not numbers.

Fix: A slash is used instead of a backslash, so it matches anything that is not a slash, or d

Change the regex to @"\b(\d+)"

Here is a working example of dotnetfiddle.net

using System;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var string1 = "500g Flour 14g Salt 7g Dry yeast 45ml Olive oil 309ml Water";

            var result = Regex.Replace(string1, @"\b(\d+)", Doubler, RegexOptions.Multiline);

            Console.WriteLine(result);

            Console.ReadKey();
        }

        private static string Doubler(Match match)
        {
            return (Convert.ToInt32(match.Value)*2).ToString();
        }
    }
}
+4

[^/d] " , d".

, \d+.

+1

datarow . : "500g Flour" - componentValue, measureType, component.Name. , , .
:
-
-

, , - . , , , .

0
void Main()
{
  string ingredients =
@"500g Flour
0.5g Salt
7g Dry yeast
45ml Olive oil
309ml Water";

  string pattern = @"(?:[0-9]+\.?[0-9]*|\.[0-9]+)";

  int multiple = 2;

  Regex.Replace(ingredients, pattern, m => (Convert.ToDecimal(m.Value)*multiple).ToString()).Dump();
}

I did this in LINQPad, so don't worry about Dump () to simply output the result. And I changed the salt to 0.5 to show that it works with non-integer numbers. This pattern is best suited for matching integers and decimals (with or without any number to decimal) so that it matches 17, 3.141592 or .5

0
source

All Articles