Regex in django models
<p>I've got a problem with regex in django models, the file name must start with letter or numer and the rest of work can caontains letters, numbers and two special signs: - and _. My code looks like:</p>

<pre><code>file_validator = validators.RegexValidator(
regex='^[a-zA-Z0-9]*[a-zA-Z0-9\_\-]*$',
message=(u'Name must start from letter or number, it can contains big and small letters, numbers and special signs: - _'),
code='invalid_file',
)
</code></pre>

<p>But when I test it in my project, when I write file name: "mike", there is an error message. What I do wrong?</p>

<p>I believe you do not need the <code>+</code> as <a href="http://stackoverflow.com/questions/39385914/regex-in-django-models#comment66098698_39385914">Avinash suggests</a>, you just need to drop the first <code>*</code> quantifier that means <em>zero or more occurrences</em>. Since it allows 0 occurrences the <em>must start with letter or number</em> rule does not work.</p>

<p>Use</p>

<pre><code>r'^[a-zA-Z0-9][\w-]*$'
</code></pre>

<p>See the <a href="https://regex101.com/r/fL2oW2/1" rel="nofollow">regex demo</a></p>

<p><strong>Pattern details</strong>:</p>

<ul>
<li><code>^</code> - start of string</li>
<li><code>[a-zA-Z0-9]</code> - 1 occurrence of an ASCII letter or digit</li>
<li><code>[\w-]*</code> - 0+ digits, letters, <code>_</code> or <code>-</code> sybmols up to</li>
<li><code>$</code> - the end of string.</li>
</ul>

<p>Note that <code>\w</code> matches ASCII letters and digits in this case since <code>re.UNICODE</code> flag is not used.</p>

<p>Also note that <code>-</code> at the end of the character class does not have to be escaped, <strong>but</strong> if you plan to add more chars to the class later, it is a good idea to keep it escaped.</p>

python regex django django-models