我想要实现的是用一个新的值替换字符串中的数字(match * int).
所以字符串输入如下:
500g Flour
14g Salt
7g Dry yeast
45ml Olive oil
309ml Water
Run Code Online (Sandbox Code Playgroud)
结果应如下所示:
1000g Flour
28g Salt
14g Dry yeast
90ml Olive oil
618 ml Water
Run Code Online (Sandbox Code Playgroud)
row["ingredients"]是一个DataRow.
这就是我所在的地方:
System.Text.RegularExpressions.
Regex.Replace(row["ingredients"].ToString(),
@"[^/d]", Delegate(Match match) { return match * 2; },
RegexOptions.Multiline);
Run Code Online (Sandbox Code Playgroud)
非常感谢任何解决方案.
第一个问题是您的正则表达式仅匹配非数字的字符。
更正:它使用正斜杠而不是反斜杠,因此它匹配除斜杠或广告之外的任何内容
将您的正则表达式更改为@"\b(\d+)"
这是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();
}
}
}
Run Code Online (Sandbox Code Playgroud)