Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace word/value in text with dynamic number

Tags:

c#

replace

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;               
}
like image 349
obdgy Avatar asked Mar 24 '23 20:03

obdgy


1 Answers

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.

like image 180
Marc Gravell Avatar answered Apr 05 '23 23:04

Marc Gravell