Note that there are some explanatory texts on larger screens.

plurals
  1. POHow does this regex find triangular numbers?
    primarykey
    data
    text
    <blockquote> <p><sub><em>Part of a series of educational regex articles, this is a gentle introduction to the concept of nested references.</em></sub></p> </blockquote> <p>The first few <a href="http://en.wikipedia.org/wiki/Triangular_number" rel="nofollow noreferrer">triangular numbers</a> are:</p> <pre><code> 1 = 1 3 = 1 + 2 6 = 1 + 2 + 3 10 = 1 + 2 + 3 + 4 15 = 1 + 2 + 3 + 4 + 5 </code></pre> <p>There are many ways to check if a number is triangular. There's this interesting technique that uses regular expressions as follows:</p> <ul> <li>Given <em>n</em>, we first create a string of length <em>n</em> filled with the same character</li> <li>We then match this string against the pattern <code>^(\1.|^.)+$</code> <ul> <li><em>n</em> is triangular if and only if this pattern matches the string</li> </ul></li> </ul> <p>Here are some snippets to show that this works in several languages:</p> <h3><a href="http://ideone.com/KoS1a" rel="nofollow noreferrer">PHP (on ideone.com)</a></h3> <pre><code>$r = '/^(\1.|^.)+$/'; foreach (range(0,50) as $n) { if (preg_match($r, str_repeat('o', $n))) { print("$n "); } } </code></pre> <h3><a href="http://ideone.com/8FxQW" rel="nofollow noreferrer">Java (on ideone.com)</a></h3> <pre><code>for (int n = 0; n &lt;= 50; n++) { String s = new String(new char[n]); if (s.matches("(\\1.|^.)+")) { System.out.print(n + " "); } } </code></pre> <h3><a href="http://ideone.com/L61sT" rel="nofollow noreferrer">C# (on ideone.com)</a></h3> <pre><code>Regex r = new Regex(@"^(\1.|^.)+$"); for (int n = 0; n &lt;= 50; n++) { if (r.IsMatch("".PadLeft(n))) { Console.Write("{0} ", n); } } </code></pre> <p>So this regex seems to work, but can someone explain how?</p> <h3>Similar questions</h3> <ul> <li><a href="https://stackoverflow.com/questions/2795065/how-to-determine-if-a-number-is-a-prime-with-regex">How to determine if a number is a prime with regex?</a></li> </ul>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

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