Loading ...

Regex: Match a string not containing a word | CodeAsp.Net

Regex: Match a string not containing a word

 /5
0 (0votes)

Let's say we have a string and we want to match that string not containing a word say alpha . I have used Regex class in order to do so. Below is the sample code:

using System;
using System.Text.RegularExpressions;

namespace SampleConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            const string inputString = "I have alpha";
            Regex regex = new Regex(@"^((?!alpha).)*$", RegexOptions.Singleline | RegexOptions.IgnoreCase);


            Console.WriteLine(regex.IsMatch(inputString)
                ? "Matched" : "String containing alpha");

            const string inputString2 = "I have beta";
            Console.WriteLine(regex.IsMatch(inputString2)
                ? "Matched" : "String not containing alpha");

            Console.ReadLine();

        }
      
    }
}

Output:

Explanation of regex:

^((?!alpha).)*$

Assert position at the beginning of the string «^»
Match the regular expression below and capture its match into backreference number 1 «((?!alpha).)*»
   Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
   Note: You repeated the capturing group itself.  The group will capture only the last iteration.  Put a capturing group around the repeated group to capture all iterations. «*»
   Assert that it is impossible to match the regex below starting at this position (negative lookahead) «(?!alpha)»
      Match the characters “alpha” literally «alpha»
   Match any single character that is not a line break character «.»
Assert position at the end of the string (or before the line break at the end of the string, if any) «$»


Created with RegexBuddy

Comments (no comments yet)

Top Posts