【问题标题】:Match number and add before replace匹配号码并在替换前添加
【发布时间】:2016-03-24 19:09:44
【问题描述】:

假设我在 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。但我不知道如何声明/编写/使用它。

欢迎任何帮助。感谢您的宝贵时间。

【问题讨论】:

  • 所以简而言之,您想使用正则表达式进行 算术 运算?
  • @noob。我需要更改数值,我想到的唯一想法是使用正则表达式。无论如何,是的,您可以考虑算术

标签: javascript c# regex


【解决方案1】:

您可以使用Match evaluator 并使用Int32.Parse 将数字解析为可以添加9 的int 值:

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 demo:

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" 

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

【讨论】:

    【解决方案2】:

    MatchEvaluatordelegate。您需要编写一个接受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));
    }
    

    【讨论】:

    • 我已将另一个标记为已接受,因为 fitted 更好...但也谢谢+1...我想我现在明白了;)
    猜你喜欢
    • 1970-01-01
    • 2018-07-28
    • 1970-01-01
    • 2010-10-29
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-07
    相关资源
    最近更新 更多