Skip to content

Instantly share code, notes, and snippets.

@mgrigajtis
Created June 15, 2018 14:25
Show Gist options
  • Save mgrigajtis/8e09906ae47bb4e390e9605f5be753c2 to your computer and use it in GitHub Desktop.
Save mgrigajtis/8e09906ae47bb4e390e9605f5be753c2 to your computer and use it in GitHub Desktop.
Generate FuzzySearch for LDAP query
/// <summary>
/// This method takes in the attribute and word (key value) that you searching
/// for in LDAP, and generates a "Fuzzy Search" string based on the key and
/// value that is passed in
/// </summary>
/// <param name="word">The value you are searching for</param>
/// <param name="attribute">The key you are searching for</param>
/// <returns>Search String</returns>
private string BuildFuzzySearchString(string word, string attribute)
{
// Create the list of fuzzy search terms
var words = new List<string>();
// Add the origingal word in, it could be spelled correctly
words.Add($"({attribute}={word})");
// We'll be using a Stringbuilder object to store our fuzzyword mutations
StringBuilder fuzzyWord = null;
// Go through and replace each letter with a wildcard, and store in the list
// This will cover a single letter misspelling, or an omitted letter
for(var i=0; i<word.Length; i++)
{
fuzzyWord = new StringBuilder(word);
fuzzyWord[i] = '*';
words.Add($"({attribute}={fuzzyWord.ToString()})");
}
// Now slice up the string so that we get results if the user only knows the first 3 or last 3 characters
var minLength = 3;
if (word.Length >= minLength)
{
fuzzyWord = new StringBuilder();
fuzzyWord.Append(word.Substring(0, minLength) + "*");
words.Add($"({attribute}={fuzzyWord.ToString()})");
fuzzyWord = new StringBuilder();
fuzzyWord.Append(Reverse(Reverse(word).Substring(0, minLength) + "*"));
words.Add($"({attribute}={fuzzyWord.ToString()})");
}
// Now if the user doesn't remember how to spell the middle of the word, we want at least twice the minimum length
if (word.Length > (minLength * 2))
{
fuzzyWord = new StringBuilder();
fuzzyWord.Append(word.Substring(0, minLength) + "*");
fuzzyWord.Append(Reverse(Reverse(word).Substring(0, minLength)));
words.Add($"({attribute}={fuzzyWord.ToString()})");
}
return string.Join("", words.ToArray());
}
/// <summary>
/// Reverses a string
/// </summary>
/// <param name="s">String to be reversed</param>
/// <returns>string except in reverse</returns>
private string Reverse(string s)
{
char[] charArray = s.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment