Saturday, April 3, 2010

ABC of regex

System.out.println(
   "abc".replaceAll("(?=(.*)).", "$1!")
); // prints "abc!bc!c!"

System.out.println(
   "abc".replaceAll(".(?<=(^.*))", "$1!")
); // prints "a!ab!abc!"

System.out.println(
   "abc".replaceAll(".(?=.*(?<=(^.*)))", "$1!")
); // prints "abc!abc!abc!"
Fun fact: non-obvious length lookbehind shouldn't even compile (Bug ID 6695369).

From regular-expressions.info:
Java takes things a step further by allowing finite repetition. You still cannot use the star or plus, but you can use the question mark and the curly braces with the max parameter specified. Java recognizes the fact that finite repetition can be rewritten as an alternation of strings with different, but fixed lengths.
Well, so much for that limitation.

No comments:

Post a Comment