Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can try (<a href="http://www.rubular.com/r/SfA309QRWF" rel="noreferrer">as seen on rubular.com</a>)</p> <pre><code>^(?=\d{5}$)1?2?3?4?5?6?7?8?9?0?$ </code></pre> <h3>Explanation</h3> <ul> <li><code>^</code> and <code>$</code> are the beginning and end of string anchors respectively</li> <li><code>\d{5}</code> is the digit character class <code>\d</code> repeated exactly <code>{5}</code> times</li> <li><code>(?=...)</code> is a positive lookahead</li> <li><code>?</code> on each digit makes each optional</li> </ul> <h3>How it works</h3> <ul> <li>First we use lookahead to assert that anchored at the beginning of the string, we can see <code>\d{5}</code> till the end of the string</li> <li>Now that we know that we have 5 digits, we simply match the digits in the order we want, but making each digit optional <ul> <li>The assertion ensures that we have the correct number of digits</li> </ul></li> </ul> <h3>regular-expressions.info</h3> <ul> <li><a href="http://www.regular-expressions.info/anchors.html" rel="noreferrer">Anchors</a>, <a href="http://www.regular-expressions.info/charclass.html" rel="noreferrer">Character Classes</a>, <a href="http://www.regular-expressions.info/repeat.html" rel="noreferrer">Finite Repetition</a>, <a href="http://www.regular-expressions.info/lookaround.html" rel="noreferrer">Lookarounds</a>, and <a href="http://www.regular-expressions.info/optional.html" rel="noreferrer">Optional</a></li> </ul> <hr> <h3>Generalizing the technique</h3> <p>Let's say that we need to match strings that consists of:</p> <ul> <li>between 1-3 vowels <code>[aeiou]</code></li> <li>and the vowels must appear in order</li> </ul> <p>Then the pattern is (<a href="http://www.rubular.com/r/SfA309QRWF" rel="noreferrer">as seen on rubular.com</a>):</p> <pre><code>^(?=[aeiou]{1,3}$)a?e?i?o?u?$ </code></pre> <p>Again, the way it works is that:</p> <ul> <li>Anchored at the beginning of the string, we first assert <code>(?=[aeiou]{1,3}$)</code> <ul> <li>So correct alphabet in the string, and correct length</li> </ul></li> <li>Then we test for each letter, in order, making each optional, until the end of the string</li> </ul> <hr> <h3>Allowing repetition</h3> <p>If each digit can repeat, e.g. <code>11223</code> is a match, then:</p> <ul> <li>instead of <code>?</code> (zero-or-one) on each digit,</li> <li>we use <code>*</code> (zero-or-more repetition) </li> </ul> <p>That is, the pattern is (<a href="http://www.rubular.com/r/GNvWYxJ8hA" rel="noreferrer">as seen on rubular.com</a>):</p> <pre><code>^(?=\d{5}$)1*2*3*4*5*6*7*8*9*0*$ </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload