title: c# generate random string based on pattern
body: <p>I'm trying to do a simple string generation based on pattern.<br>
  My idea was to use Regex to do simple replace.
  I've started with simple method:</p>
  
  <pre><code>private static string parseTemplate(string template)
  {
      return Regex.Replace(template, @"(\[d)((:)?([\d]+)?)\]", RandomDigit());
  }
  
  private static string RandomDigit()
  {
      Random r = new Random();
      return r.Next(0, 9).ToString();
  }
  </code></pre>
  
  <p>What this does for now is replacing groups like <code>[d]</code>, <code>[d:3]</code> with what supposed to be random digit.<br>
  Unfortunately every group is replaced with the same digit, for example if I put <code>test [d][d][d:3]</code> my method will return <code>test 222</code>.<br>
  I would like to get different digit in every place, like <code>test 361</code>.</p>
  
  <p>Second problem I have is way to handle length:</p>
  
  <p>right now I must specify <code>[d]</code> for every digit I want, but it would be easier to specify <code>[d:3]</code> and get the same output.</p>
  
  <p><strong>I know that there is a project called <a href="https://github.com/moodmosaic/Fare" rel="nofollow">Fare</a>, but I would like to do this without this library</strong></p>
  
  <p>For now I only search for <code>[d]</code>, but is this method will work fine there won't be a problem to add other groups for example: <code>[s]</code> for special characters or any other type of patters.</p>
  
  <p><strong>Edit1</strong></p>
  
  <p>As it was suggested I changed Random to a static variable like so:</p>
  
  <pre><code>private static string parseTemplate(string template)
      {
          return Regex.Replace(template, @"(\[d)((:)?([\d]+)?)\]", RandomDigit());
      }
  
      private static Random r = new Random();
  
      private static string RandomDigit()
      {
          return r.Next(0, 9).ToString();
      }
  </code></pre>
  
  <p>Problem is that when I call my code like so:</p>
  
  <pre><code>Console.WriteLine(parseTemplate("test [d:2][d:][d]"));
  Console.WriteLine(parseTemplate("test [d:2][d:][d]")); 
  </code></pre>
  
  <p>I get output like this</p>
  
  <pre><code>test 222
  test 555
  </code></pre>
  
  <p>I would like output like this (for example):</p>
  
  <pre><code>test 265
  test 962
  </code></pre>
  
  <p>I think that problem is with <code>Regex.Replace</code> which calls my <code>RandomDigit</code> only once.</p>