How to make regex that matches a number with commas for every three digits?
<p>I am a beginner in Python and in regular expressions and now I try to deal with one exercise, that sound like that:</p>

<blockquote>
  <p>How would you write a regex that matches a number with commas for
  every three digits? It must match the following:</p>
  
  <p>'42'</p>
  
  <p>'1,234'</p>
  
  <p>'6,368,745'</p>
  
  <p>but not the following:</p>
  
  <p>'12,34,567' (which has only two digits between the commas)</p>
  
  <p>'1234' (which lacks commas)</p>
</blockquote>

<p>I thought it would be easy, but I've already spent several hours and still don't have write answer. And even the answer, that was in book with this exercise, doesn't work at all (the pattern in the book is <code>^\d{1,3}(,\d{3})*$</code>)</p>

<p>Thank you in advance!</p>

<p>The answer in your book seems correct for me. It works on the test cases you have given also.  </p>

<pre><code>(^\d{1,3}(,\d{3})*$)
</code></pre>

<p>The <code>'^'</code> symbol tells to search for integers at the start of the line. <code>d{1,3}</code> tells that there should be at least one integer but not more than 3 so ;</p>

<pre><code>1234,123 
</code></pre>

<p>will not work.</p>

<pre><code>(,\d{3})*$
</code></pre>

<p>This expression tells that there should be one comma followed by three integers at the end of the line as many as there are.</p>

<p>Maybe the answer you are looking for is this:</p>

<pre><code>(^\d+(,\d{3})*$)
</code></pre>

<p>Which matches a number with commas for every three digits without limiting the number being larger than 3 digits long before the comma.</p>

python regex