For ex. I have string
string text = @"Today is {Rand_num 15-22} day. {Rand_num 11-55} number of our trip.";
I need to replace every Rand_num constraction with rand number (between stated numbers 15-22 or 11-55)
Tried smth but don't know what to do next
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;
}
How about:
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();
});
Obviously output will vary, but I get:
Today is 21 day. 25 number of our trip.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With