How to match a string not containing a substring using RegEx in C#

1 Answer

0 votes
using System;
using System.Text.RegularExpressions;

// ^: 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 bool StringNotContainingSubstring(string pattern, string text) {
        Regex re = new Regex(pattern, RegexOptions.IgnoreCase);
        
        return re.IsMatch(text);
    }

    static void Main() {
        string pattern = "^((?!notype).)*$";

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

 
 
 
/*
run:
     
False
False
False
False
False
True
True
True
True
     
*/
 

 



answered Feb 27, 2025 by avibootz

Related questions

...