4

例如。我有字符串

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

我需要用 rand 数替换每个 Rand_num 收缩(在规定的数字 15-22 或 11-55 之间)

尝试了但不知道下一步该怎么做

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;               
}
4

2 回答 2

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天。我们旅行的25号。

于 2013-05-22T12:23:06.513 回答
-1

您可以使用随机方法,如果适合您,请检查代码片段。

Random random=new Random();
string text=String.Format("Today is {0} day. {1} number of our trip.", random(15-22), random(11-15));
于 2013-05-22T12:23:35.297 回答