Wednesday, December 21, 2011

Regex and Lookahead/Lookbehind

E.g. to remove all @Component annotations from non-"Default" classes:

search for (negative lookahead):
@Component\npublic class (?!Default)

replace with:
public class

negative lookahead: q(?!u) matches a "q" not followed by a "u"

positive lookahead:  q(?=u) matches a q that is followed by a u, without making the u part of the match

If you want to store the match of the regex inside a backreference, you have to put capturing parentheses around the regex inside the lookahead, like this:(?=(regex))

negative lookbehind: (?<!a)b matches a "b" that is not preceded by an "a", using negative lookbehind.

positive lookbehind: (?<=a)b matches the b (and only the b) in cab