处理完比赛后替换比赛

时间:2015-09-01 13:10:02

标签: c# regex

在我的程序中,我正在实现用变量值替换的标记。

这样的标记是 #INT [1-5] (意味着它会被1到5之间的随机int替换。

我已经写了正则表达式来匹配令牌: #INT [\ d + - \ d +]

但是我不知道如何替换令牌(在处理完比赛并计算随机数之后。

到目前为止,我有以下内容:

Random random = new Random();
Regex regex = new Regex(@"#INT\[\d+-\d+\]");
MatchCollection matches = regex.Matches("This is one of #INT[1-5] tests");
foreach (Match m in matches)
{
    if (m.Success)
    {
        var ints = m.Value.Split('-').Select(x => Convert.ToInt32(x)).ToArray();
        int intToInsert = random.Next(ints[0], ints[1]);
        //now how do I insert the int in place of the match? 
    }
}

1 个答案:

答案 0 :(得分:2)

我认为您需要将匹配评估器与Regex.Replace一起使用,并使用正则表达式中数字周围的捕获组:

var regex = new Regex(@"#INT\[(\d+)-(\d+)\]");
//                            ^   ^ ^   ^
var res = regex.Replace("This is one of #INT[1-5] tests", m => 
            random.Next(Convert.ToInt32(m.Groups[1].Value), Convert.ToInt32(m.Groups[2].Value)).ToString());

结果:This is one of 2 testsThis is one of 3 tests,...

可以使用m.Groups[n].Value访问捕获的文本。

相关问题