Given such Java
Regex
codes:
Pattern pattern = Pattern.compile("[^(bob)(alice)(kitty)]");
String s = "a";
Matcher matcher = pattern.matcher(s);
boolean bl = matcher.find();
System.out.println(bl);
The output is false
. Why? The regex [^(bob)(alice)(kitty)]
matches any things except bob
, alice
or kitty
. Then the result should be true, right?
To match any character except a list of excluded characters, put the excluded charaters between [^ and ] . The caret ^ must immediately follow the [ or else it stands for just itself. The character '.
The ?! n quantifier matches any string that is not followed by a specific string n.
Matching a Single Character Using Regex ' dot character in a regular expression matches a single character without regard to what character it is. The matched character can be an alphabet, a number or, any special character.
The backslash \ is an escape character in Java Strings. That means backslash has a predefined meaning in Java. You have to use double backslash \\ to define a single backslash. If you want to define \w , then you must be using \\w in your regex.
Because your regex is not doing what you think it should be doing.
Use this regex with Negative lookahead:
Pattern pattern = Pattern.compile("^(?!bob|alice|kitty).*$");
Your regex: [^(bob)(alice)(kitty)]
is using a character class and inside a character class there are no groups.
(?!bob|alice|kitty)
is negative lookahead that means fail the match if any of these 3 words appear at start of input.^
and $
to make sure we're not matching from middle of the string.If you want to avoid matching these 3 words anywhere in input then use this regex:
^(?!.*?(?:bob|alice|kitty)).*$
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With