How to match a string not containing a substring using RegEx in Java

1 Answer

0 votes
import java.util.regex.Pattern;
import java.util.regex.Matcher;

// ^: Matches the beginning of the string
// (?!notype): asserts that the current position in the string is not followed by the 
//             substring "notype"
// .: Matches any single character (except newline characters)
// *: Matches the preceding group (((?!notype).)) zero or more times
// $: Matches the end of the string

class Program {
    static boolean stringNotContainingSubstring(String pattern, String text) {
        Pattern re = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
        Matcher matcher = re.matcher(text);
        
        return matcher.find();
    }

    public static void main(String[] args) {
        String pattern = "^((?!notype).)*$";

        System.out.println(stringNotContainingSubstring(pattern, " notype"));
        System.out.println(stringNotContainingSubstring(pattern, "notype "));
        System.out.println(stringNotContainingSubstring(pattern, "notypevar"));
        System.out.println(stringNotContainingSubstring(pattern, "anotypevar"));
        System.out.println(stringNotContainingSubstring(pattern, "anotype"));
        System.out.println(stringNotContainingSubstring(pattern, "The only approval you need is your own"));
        System.out.println(stringNotContainingSubstring(pattern, "Follow your dreams"));
        System.out.println(stringNotContainingSubstring(pattern, "Never regret anything that made you smile"));
        System.out.println(stringNotContainingSubstring(pattern, "A programming language"));
    }
}


 
/*
run:
     
false
false
false
false
false
true
true
true
true
     
*/

 



answered Feb 28, 2025 by avibootz

Related questions

...