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>You can go with this (which is a slightly improved version of what the book specifies):</p>

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

<p><a href="https://regex101.com/r/amGFa4/2" rel="nofollow">Demo on Regex101</a></p>

python regex