Replace the word / value in the text with a dynamic number

For example, I have a string

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

I need to replace each Rand_num constraction with a rand number (between declared numbers 15-22 or 11-55)

I tried, but I do not 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; } 
+4
source share
2 answers

What 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 the output will be different, but I get:

Today is 21 days. 25 numbers of our trip.

+8
source

You can use Random Method, Check Code Snippet if it suits you.

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

Source: https://habr.com/ru/post/1482151/


All Articles