 <p>If your string can be ANY length and you want to match the cases when you have 0 to 3 charaters you should use:</p> <pre><code>\d?\d?\d?\d?$ </code></pre> <p>or, if the regex engine understands it: </p> <pre><code>\d{0-4}$ </code></pre>