wybourn wybourn - 4 months ago 11
Java Question

Java negative lookahead not working

I have the following regex

^(?!0{8})
, which should match any string that isn't 8 zeros. I can't see why this isn't working. I.e, 12345678 does not match.

I need to use regex as I'm using this in a
@Pattern
annotation, so I can't just do an equality check.

I've tested it on this site https://regex101.com/ and it seems perfectly fine.

Any ideas?

Answer

You have made some mistakes in your regex. Checking if a string contains only 8 zeros. (According to your question, that is what you want to avoid) can be done with the regex "^(0{8})$". This regex will return true if there are 8 zeroes in a row, and that is the only content in the string. ^ matches the beginning and $matches the end.

You can use java to negate the result.

    String s = "123456789";
    System.out.println(!s.matches("^(0{8})$"));