Reputation: 678
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?
Upvotes: 1
Views: 240
Reputation: 626748
Your lookahead lacks the $
end of string anchor, and disallows matching any string starting with 8 zeros.
You need to use
^(?!0{8}$)
^
or - if the annotation pattern must match the entire string:
^(?!0{8}$).*$
Upvotes: 2
Reputation: 5802
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})$"));
Upvotes: 2