The person whom comes up with this regex for primality test demonstrated ingenuity.
It basically performed a search for NxM where N>1 and M>1.
For those whom may find this regex daunting. Basically
(11+?) is looking for N where N > 1 since there must be at least 2 '1's for this regex to match.
(11+?)\1+ is basically looking for
MxN since \1 is a back reference to the matched
(11+?) result. it has to be
NNNNNN..... for M times and M Is also at least 2 times.
With the backtracking behaviour of regex, the regex engine will attempt to match exhaustively for any possible NNNNNNNN....N <--- total M times. N can be any number of "1s" but there must always be >=2 sets of N(1s).
That is why 9 -> NNN -> 3N x 3M, while 8 -> NNNN -> 2N x 4M. While 8 can be expressed as 4x2, but in the case of this regex, it will not match since it is non-greedy for (11+?).
On the other hand, if you use this slightly changed regex, which I have verified to be working too
/^1?$|^(11+)\1+$/, it will match
4Nx2M for 8,
5N*2M for 10.
