0

I want to create a regex that allows only class names not ending with Impl. I'v read that "not ends with" could be tested with a negative lookahead (?!), but I cannot find a working (Java) regex.

I tried

[A-Z][A-Za-z\d]*?(?!Impl)

but it matches SomeImpl, what shouldn't be the case.

What regex wouldn't match class names ending with Impl?

Peter Boughton
  • 110,170
  • 32
  • 120
  • 176
deamon
  • 89,107
  • 111
  • 320
  • 448

1 Answers1

5

A negative lookahead wont work because - with the *? (lazy zero-or-more) quantifier - it'll check at S and find no Impl immediately ahead so the match succeeds.

If you changed to a greedy quantifier (change * to *?) it would still fail because you would be at the end of the string - there is no "ahead" to look at.

Instead you want to use a negative lookbehind to check the previous content, i.e.

[A-Z][A-Za-z\d]*(?<!Impl)

(You may or not want $ at the end of that, depending on where the pattern is used)

Side note: not directly relevant here, but useful to know is that (in Java regex) a lookbehind must have a limited width - you can't use * or + quantifiers, and must instead use limited numerical quantifiers, e.g. {0,99}


But unless the pattern itself is important (or you're working in a context where you must use regex), a simpler option would be String.endsWith, like so:

! mystring.endsWith('Impl')
Peter Boughton
  • 110,170
  • 32
  • 120
  • 176
  • super observation buddy +1 – aelor Apr 09 '14 at 13:50
  • aelor, I've just updated my explanation on why the lookahead fails - does it make sense? – Peter Boughton Apr 09 '14 at 14:00
  • but i used to know that a lazy quantifier matches the least. `.*` should only match till the end ? – aelor Apr 09 '14 at 14:02
  • `String.endsWith` is not an option in my case, because I need the pattern to configure IntelliJ IDEA inspections. – deamon Apr 09 '14 at 14:03
  • Not sure I understand the question - a `.*` will match until the end then backtrack if necessary, whilst `.*?` will do one character at a time, unless a later backtrack requires it to consume more. – Peter Boughton Apr 09 '14 at 14:06