9am

Fuzzy RegexMatcher

In Programming, Strings on September 4, 2010 at 2:41 pm

/*
This Fuzzy RegexMatcher does not handle *,?, ^ etc., but, it takes in a tolerance/forgiveness factor.
With a forgiveness value of 1, regex “ac” would match strings like “abc” or “ad” or “c”.  With a forgiveness factor of 0, the match would fail.
*/

using System;
namespace StringHelpers
{
public static partial class RegexMatcher
{
public static bool AreSimilar(char[] str, char[] pattern, int forgiveness)
{
// Args check todo
for (int i = 0; i <= str.Length – pattern.Length; i++)
{
if (AreSimilar(str, pattern, i/*str index*/, 0/*pattern index*/, forgiveness)) return true;
}
return false;
}
private static bool AreSimilar(char[] str, char[] pattern, int si, int pi, int forgiveness)
{
if (pi >= pattern.Length) return true;
if (si >= str.Length) return false;
if (str[si] == pattern[pi])
{
return AreSimilar(str, pattern, si + 1, pi + 1, forgiveness);
}
else if (forgiveness > 0)
{
return AreSimilar(str, pattern, si, pi + 1, forgiveness – 1)|| AreSimilar(str, pattern, si + 1, pi + 1, forgiveness – 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: