匹配数字并在替换之前添加

Match number and add before replace

本文关键字:添加 替换 数字      更新时间:2023-09-26

假设我在text.txt中有:

prop:"txt1"  prop:'txt4'  prop:"txt13"

我希望它变成(加9):

prop:"txt10"  prop:'txt13'  prop:"txt22"

在javascript中,它将是:

var output = input.replace(/prop:(['"])txt('d+)'1/g, function(match, quote, number){
    return "prop:" + quote + "txt" + (parseInt(number) + 9) + quote;
});

我正在尝试用C#对上面的代码进行编码:

string path = @"C:/text.txt";
string content = File.ReadAllText(path);
File.WriteAllText(path, Regex.Replace(content, "prop:([''"])txt(''d+)''1", ?????));

Visual Studio显示第三个参数应该是MatchEvaluator evaluator。但我不知道如何声明/写入/使用它。

欢迎任何帮助。谢谢你抽出时间。

您可以使用Match计算器并使用Int32.Parse将数字解析为int值,您可以将9添加到:

Regex.Replace(content, @"prop:(['""])txt('d+)'1", 
m => string.Format("prop:{0}txt{1}{0}",
     m.Groups[1].Value, 
    (Int32.Parse(m.Groups[2].Value) + 9).ToString()))

查看IDEONE演示:

var content = "prop:'"txt1'"  prop:'txt4'  prop:'"txt13'"";
var r = Regex.Replace(content, @"prop:(['""])txt('d+)'1", 
    m => string.Format("prop:{0}txt{1}{0}",
         m.Groups[1].Value, 
        (Int32.Parse(m.Groups[2].Value) + 9).ToString()));
Console.WriteLine(r); // => prop:"10"  prop:'13'  prop:"22" 

请注意,我使用的是逐字字符串文字,以便使用单个反斜杠来转义特殊字符并定义速记字符类(然而,在逐字字符串文字中,双引号必须加倍以表示单个文字双引号)。

MatchEvaluator是一个委托。您需要编写一个使用Match并返回替换值的函数。一种方法如下所示:

private static string AddEvaluator(Match match)
{
    int newValue = Int32.Parse(match.Groups[2].Value) + 9;
    return String.Format("prop:{0}txt{1}{0}", match.Groups[1].Value, newValue)
}
public static void Main()
{
    string path = @"C:/text.txt";
    string content = File.ReadAllText(path);
    File.WriteAllText(path, Regex.Replace(content, "prop:([''"])txt(''d+)''1", AddEvaluator));
}