0 Comments

At work, we had to do wildcard searches using regular expressions to match allowed domain names. For instance, this expression “*.madskristensen.dk” should match “www.madskristensen.dk”.

So, my boss Jimmi wrote a method that he allowed me to post here. Here are some examples on how to use it:

IsDomainValid( "www.madskristensen.dk" , "*.madskristensen" ); is true

IsDomainValid( "www.madskristensen.dk" , "www.madskristensen*" ); is true

IsDomainValid( "www.madskristensen.dk" , "madskristensen*" ); is false

IsDomainValid( "www.madskristensen.dk" , "*mads*.dk" ); is true
IsDomainValid( "www.madskristensen.dk" , "www.*.dk" ); is true

Here is the method.

/// <summary>

/// Checks if a wildcard string matches a domain

/// </summary>

public static bool IsDomainValid( string domain, string domainToCheck)

{

if (domainToCheck.Contains( "*" ))

{

string checkDomain = domainToCheck;

if (checkDomain.StartsWith( "*." ))

checkDomain = "*" + checkDomain.Substring(2, checkDomain.Length - 2);

return DoesWildcardMatch(domain, checkDomain);

}

else

{

return domainToCheck.Equals(domain, StringComparison .OrdinalIgnoreCase);

}

}

/// <summary>

/// Performs a wildcard (*) search on any string.

/// </summary>

public static bool DoesWildcardMatch( string originalString, string searchString)

{

if (!searchString.StartsWith( "*" ))

{

int stop = searchString.IndexOf( '*' );

if (!originalString.StartsWith(searchString.Substring(0, stop)))

return false ;

}

if (!searchString.EndsWith( "*" ))

{

int start = searchString.LastIndexOf( '*' ) + 1;

if (!originalString.EndsWith(searchString.Substring(start, searchString.Length - start)))

return false ;

}

Regex regex = new Regex (searchString.Replace( @"." , @"\." ).Replace( @"*" , @".*" ));

return regex.IsMatch(originalString);

}

You can also use the DoesWildcardMatch method alone.

DoesWildcardMatch( "hello world" , "*world" ); is true