Monday, July 5, 2010

Split into powers of 2 using regex

There are so many levels of abuse here it's not even funny.
for (String s :
   new String(new char[(1 << 8) - 1])
   .split("(?=(.*))(?<=(?<=(^.*))\\G.*)(?<=(?=\\2\\2.\\1)^.*)")
) {
   System.out.printf("%s ", s.length());
} // "1 2 4 8 16 32 64 128 "
I think there's still room for "improvement", though...
"Improvements", as Java string literals:
"(?=(.*))(?<=(?<=(^.*))\\G.*)(?<=(?=\\2\\2.\\1)^.*)"
"(?=(.*))(?<=(?<=(^.*))\\G.*)(?<=(?=\\2.\\1)\\G.*)"