Wednesday, June 23, 2010

Regex insanity

Now the most insane regex I've written:
String[] tests = {
   "APPLE juice; APPLE cream; APPLE pie; ORANGE sherbet; ORANGE punch; ",
   "APPLE juice; ORANGE punch; ",
   "APPLE juice; ORANGE punch; ORANGE sherbet; ",
   "APPLE juice; ORANGE punch; LEMON pie; ",
   "APPLE juice; APPLE pie; APPLE cream; ",
   "Tommy eats; Tommy sleeps; Tommy drinks; Jamie tosses; Jamie turns; Amy blinks; "
};
for (String test : tests) {         
   System.out.println(test.replaceAll(
      "(?<=^(?=.*\\b(\\w+) \\w+; \\G).*)?(?:\\1 |(\\w+ ))(\\w+; )",
      "$2$3"
   ));
}
This prints, believe it or not:
APPLE juice; cream; pie; ORANGE sherbet; punch; 
APPLE juice; ORANGE punch; 
APPLE juice; ORANGE punch; sherbet; 
APPLE juice; ORANGE punch; LEMON pie; 
APPLE juice; pie; cream; 
Tommy eats; sleeps; drinks; Jamie tosses; turns; Amy blinks; 
It'll be fun to go back to this, say oh, five years from now, and try to figure out what's going on here...

No comments:

Post a Comment