With anchors, it will match binary numbers divisible by 3. though I haven't figured out exactly why...

I think you are right, assuming the empty string is divisble by 3.

Here is why:

To start at the front of the regex, /^0*$/ will match a number made up of zero or more zeros. Assuming the empty string qualifies as being divisible by 3, all matching strings are divisble by 3: they all have the value 0.

Putting zeroes at the back of the number just results in numbers that are twice as large and thus divisible by 3, if the original number was.

Going to the other side of the alternation, and simplifying we see /^(11)*$/, that is: a string consisting of zero or more pairs of adjacent 1-bits. It is easy to show that the value produced by every pair is divisible by 3: 2n+1 + 2n = 3 * 2n.

We've already seen that zero repetitions of the inner group of /^(1(01*0)*1)*$/ result in a number divisible by 3. Mixing substrings of two zeroes into a binary number will not alter its divisibilty by 3. The cases of adding to the front and back are obvious, but what happens when they are put in between? In that case the 1 representing 2n gets to represent 2n+2, which will just add 3 * 2n to the sum of the digits.

What happens when we start using (and repeating) the 1 from the group in /1(01*0)1/? For every 1, you shift the left-most 1 one position to the left, doubling its value and obtain a 1 representing half the value of the left-most 1 before shifting. This adds 2n + 2n-1 = 3 * 2n-1. So the number is still divisible by 3.

I think that covers all variations... I could have dreamt typing in some of them, though. ;-)

— Arien


In reply to Re(2): Regex refresher by Arien
in thread Regex refresher by FoxtrotUniform

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.