title: Regular Expression for exactly N elements, not less, not more
body: <p>I am trying to figure out what the regex for finding matches with exactly N occurrences, not less, not more, of a group of characters. It looks like a pretty simple task, but I have not been able to find the proper regex for it.</p>
  
  <p>More specifically, I want a regex that tells whether a given string contains exactly 3 digits - not less, not more.</p>
  
  <p>I thought I would be able to achieve it simply by treating the 3 digits as a group and adding a quantifier of {1} after it, but it does not work.</p>
  
  <p>Alternately, I expected [0-9][0-9][0-9] to work as well, but again it does not. Both <em>regexes</em> return the very same results, for the an input set as
  1, 12, 123, 1234, 12345.</p>
  
  <p>Below is a code sample that performs what I tried, as described above.</p>
  
  <pre><code>class Program
  {
      static void Main(string[] args)
      {
          List&lt;Regex&gt; regexes = new List&lt;Regex&gt; { new Regex("\\d{3}"), new Regex("[0-9][0-9][0-9]"), new Regex("(\\d{3}){1}") };
          List&lt;int&gt; numbers = new List&lt;int&gt; { 1, 12, 123, 1234, 12345 };
  
          foreach(Regex regex in regexes)
          {
              Console.WriteLine("Testing regex {0}", regex.ToString());
              foreach (int number in numbers)
              {
                  Console.WriteLine(string.Format("{0} {1}", number, regex.IsMatch(number.ToString()) ? "is a match" : "not a match"));
              }
              Console.WriteLine();
          }
      }
  }
  </code></pre>
  
  <p>The output to the program above is:
  <img src="https://i.stack.imgur.com/mIRM6.png" alt="enter image description here"></p>
  
  <p>Clearly, only 123 is a match, from all the input values.
  What would be the regular expression that treats "123" alone as a match ?</p>