Tuesday, March 9, 2010

Looking behind as far as the eyes could see...

System.out.println(
   java.util.Arrays.deepToString(
      "This works! Yes, really!! Try it! JUST DO IT!!!".split("(?<=!++)")
   )
); // [This works!,  Yes, really!!,  Try it!,  JUST DO IT!!!]
 
The above snippet works. I had to experiment with the different quantifiers, and neither greedy nor reluctant worked, but somehow possessive does what I wanted. And I'm not sure how and why.

It turns out that it isn't supposed to work. That pattern isn't supposed to be compilable; a PatternSyntaxException should've been thrown. That it compiles is a bug (ID 6695369); that it works is mind-boggling. So, unlike the case in the bug report, this pattern doesn't "fail silently" -- it "works unexpectedly"!!!

For what it's worth, the "right" pattern to use is "(?<=!)(?!!)" (credit to Alan Moore on stackoverflow.com).

No comments:

Post a Comment