Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Regex-matches anything except three specific string

Tags:

java

regex

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?

like image 491
chrisTina Avatar asked Dec 11 '14 16:12

chrisTina


People also ask

How do you ignore something in regex?

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 '.

What is ?! In regex?

The ?! n quantifier matches any string that is not followed by a specific string n.

Does regex match anything?

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.

What does \\ mean in Java regex?

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.


1 Answers

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.
  • Important to use anchors ^ 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)).*$
    

RegEx Demo

like image 199
anubhava Avatar answered Oct 18 '22 11:10

anubhava