What I'm trying to achieve is to replace the numbers in the string with a new values calculated from the (match * int)
.
So the string input looks like:
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 a DataRow
.
This is where I'm at:
System.Text.RegularExpressions.
Regex.Replace(row["ingredients"].ToString(),
@"[^/d]", Delegate(Match match) { return match * 2; },
RegexOptions.Multiline);
Any solution is greatly appreciated.
The first problem is that your regex is only matching characters that are not a digit.
Correction: It is using forward slashes instead of a backslash, so it's matching anything that is not a slash or a d
Change your regex to @"\b(\d+)"
Here's a working example on 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();
}
}
}
[^/d]
means "any character except slash or the letter d
".
To match a number, use \d+
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With