The solution makes use of Regex class in .NET and supports both '*' and '?' wild cards.
private bool IsWildcardMatch(String wildcard, String text, bool casesensitive)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder(wildcard.Length + 10);
sb.Append("^");
for (int i = 0; i < wildcard.Length; i++)
{
char c = wildcard[i];
switch(c)
{
case '*':
sb.Append(".*");
break;
case '?':
sb.Append(".");
break;
default:
sb.Append(System.Text.RegularExpressions.Regex.Escape(wildcard[i].ToString()));
break;
}
}
sb.Append("$");
System.Text.RegularExpressions.Regex regex;
if (casesensitive)
regex = new System.Text.RegularExpressions.Regex(sb.ToString(), System.Text.RegularExpressions.RegexOptions.None);
else
regex = new System.Text.RegularExpressions.Regex(sb.ToString(), System.Text.RegularExpressions.RegexOptions.IgnoreCase);
return regex.IsMatch(text);
}
I picked up the above sample from http://adamsen.wordpress.com/2008/10/16/c-string-wildcard-match/ but it only supported '*" and not '?'.
I added a case block to support ? as well.
vaibhav
Tuesday, February 9, 2010
String matching with pattern having wildcard characters in C#
Posted by
vaibhav
at
9:00 AM
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment