I try to use Eclipse’s RegEx search function to search for the words ‘foo’ or ‘bar’, ignoring comments.
This is what I’ve got so far:
^(?!\s*(//|\*)).*(foo|bar)
The comment restrictions of my solutions are okay for me (anyway, if somebody has a better solution without dramatically extending the regex, I’d be glad to hear about it):
- Single-line comments have to start at the beginning of the line, maybe indented (so I don’t care that
return null; // foowon’t be ignored). - Multi-line comments start at the beginning of the line with a single asterisk, maybe indended (so
/* foowon’t be ignored, whilebar \n * foowill be ignored even though it’s not really a comment).
My problem is, that now the whole line up to (and including) ‘foo’ or ‘bar’ is highlighted in the search results. I only want ‘foo’ or ‘bar’ (or both, if both appear in the same line) to be highlighted.
I tried to include a positive look-ahead (in several variants) to achieve this:
^(?!\s*(//|\*))(?=.*)(foo|bar)
This results in no results. I don’t understand why. Thanks for any hint!
The problem is that lookaround assertions don’t actually match and consume any text. So in the regex
the texts
fooorbarcan only be matched at the start of the line because the regex engine hasn’t yet moved after matching all the lookaheads.That means if you don’t want the text leading up to
foo/barto be matched, you need a look*behind* assertion instead. However, only .NET and JGSoft regex engines support indefinite quantifiers like the asterisk inside a lookbehind assertion. Java/Eclipse do not support this.In .NET, you could search for