用动态数字替换文本中的单词/值

时间:2013-05-22 12:17:59

标签: c# replace

对于前。我有字符串

string text = @"Today is {Rand_num 15-22} day. {Rand_num 11-55} number of our trip.";

我需要用兰特数替换每个Rand_num构造(在规定的数字15-22或11-55之间)

尝试了smth,但不知道接下来该做什么

string text = @"Today is {Rand_num 15-22} day. {Rand_num 11-55} number of our trip.";
if (text.Contains("Rand_num"))
{              
    string groups1 = Regex.Match(text, @"{Rand_num (.+?)-(.+?)}").Groups[1].Value;
    string groups2 = Regex.Match(text, @"{Rand_num (.+?)-(.+?)}").Groups[2].Value;               
}

2 个答案:

答案 0 :(得分:8)

怎么样:

Random rand = new Random();
text = Regex.Replace(text, @"{Rand_num (.+?)-(.+?)}", match => {
    int from = int.Parse(match.Groups[1].Value),
        to = int.Parse(match.Groups[2].Value);
    // note end is exclusive
    return rand.Next(from, to + 1).ToString();
});

显然输出会有所不同,但我得到:

  

今天是21天。我们旅行的次数是多少。

答案 1 :(得分:-1)

您可以使用随机方法,检查代码段是否适合您。

Random random=new Random();
string text=String.Format("Today is {0} day. {1} number of our trip.", random(15-22), random(11-15));