9am

RegexMatcher

In Programming, Strings on September 4, 2010 at 2:24 pm
/* Regex Pattern Matching
Handles ^, $ and *
*/
using System;
namespace StringHelper
{
public static partial class RegexMatcher
{
public static bool IsMatch(char[] str, char[] pattern)
{
if (pattern[0] == ‘^’)
return IsMatch(str, 0, pattern, 1);
for (int i = 0; i < str.Length; i++)
{
if (IsMatch(str, i, pattern, 0)) return true;
}
return false;
}
// handle ? *
public static bool IsMatch(char[] str, int si, char[] pattern, int pi)
{
// pattern is over. IsMatch is true.
if (pattern == null || pi >= pattern.Length) return true;
if (pattern[pi] == ‘$’)
{
if (si == str.Length) return true;
else return false;
}
// pattern is not over.
if (si >= str.Length) return false;
// pattern is not exhausted and str is not exhausted.
if (pattern[pi] == ‘?’)
return IsMatch(str, si + 1, pattern, pi + 1) || IsMatch(str, si, pattern, pi + 1);
if (pattern[pi] == ‘*’)
{
for (int i = si; i < str.Length; i++)
if (IsMatch(str, i, pattern, pi + 1)) return true;
}
if (pattern[pi] == str[si])
return IsMatch(str, si + 1, pattern, pi + 1);
return false;
}
}
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: