Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><code>^((.)(?1)\2|.?)$</code></p> <p>The <code>^</code> and <code>$</code> asserts the beginning and the end of the string respectively. Let us look at the content in between, which is more interesting:</p> <pre><code>((.)(?1)\2|.?) 1------------1 // Capturing group 1 2-2 // Capturing group 2 </code></pre> <p>Look at the first part <code>(.)(?1)\2</code>, we can see that it will try to match any character, and that same character at the end (back reference <code>\2</code>, which refers to the character matched by <code>(.)</code>). In the middle, it will recursively match for the whole capturing group 1. Note that there is an implicit assertion (caused by <code>(.)</code> matching one character at the beginning and <code>\2</code> matching the same character at the end) that requires the string to be at least 2 characters. The purpose of the first part is chopping the identical ends of the string, recursively.</p> <p>Look at second part <code>.?</code>, we can see that it will match one or 0 character. This will only be matched if the string initially has length 0 or 1, or after the leftover from the recursive match is 0 or 1 character. The purpose of the second part is to match the empty string or the single lonely character after the string is chopped from both ends.</p> <p>The recursive matching works:</p> <ul> <li>The whole string must be palindrome to pass, asserted by <code>^</code> and <code>$</code>. We cannot start matching from any random position.</li> <li>If the string is &lt;= 1 character, it passes.</li> <li>If the string is > 2 characters, whether it is accepted is decided by the first part only. And it will be chopped by 2 ends if matches.</li> <li>The leftover if matches, can only be chopped by the 2 ends, or passes if its length is &lt;= 1.</li> </ul>
 

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