Mega Code Archive

 
Categories / C# Book / 11 Regular Expression Basics
 

0649 Use Lookahead to validate a strong password

Suppose a password has to be at least six characters and contain at least one digit. using System; using System.Text.RegularExpressions; class Program { static void Main(string[] args) { string password = "..."; bool ok = Regex.IsMatch (password, @"(?=.*\d).{6,}"); } } (?!expr) is the negative lookahead construct. This requires that the match not be followed by expr. using System; using System.Text.RegularExpressions; class Program { static void Main(string[] args) { string regex = "(?i)C#(?!.*(XML|Java))"; Console.WriteLine (Regex.IsMatch ("C#! Java...", regex)); Console.WriteLine (Regex.IsMatch ("C#! SQL!", regex)); } } The output: False True (?<=expr) denotes positive lookbehind and requires that a match be preceded by a specified expression. (?<!expr), denotes negative lookbehind and requires that a match not be preceded by a specified expression. using System; using System.Text.RegularExpressions; class Program { static void Main(string[] args) { string regex = "(?i)(?<!Java.*)Sql"; Console.WriteLine (Regex.IsMatch ("Java, Sql...", regex)); Console.WriteLine (Regex.IsMatch ("Java C#!", regex)); } } The output: False False