<p>Hey, I'm using <a href="http://en.wikipedia.org/wiki/Levenshtein_distance" rel="nofollow noreferrer">Levenshteins</a> algorithm to get distance between source and target string.</p>

<p>also I have method which returns value from 0 to 1:</p>

<pre><code>/// &lt;summary&gt;
/// Gets the similarity between two strings.
/// All relation scores are in the [0, 1] range, 
/// which means that if the score gets a maximum value (equal to 1) 
/// then the two string are absolutely similar
/// &lt;/summary&gt;
/// &lt;param name="string1"&gt;The string1.&lt;/param&gt;
/// &lt;param name="string2"&gt;The string2.&lt;/param&gt;
/// &lt;returns&gt;&lt;/returns&gt;
public static float CalculateSimilarity(String s1, String s2)
{
    if ((s1 == null) || (s2 == null)) return 0.0f;

    float dis = LevenshteinDistance.Compute(s1, s2);
    float maxLen = s1.Length;
    if (maxLen &lt; s2.Length)
        maxLen = s2.Length;
    if (maxLen == 0.0F)
        return 1.0F;
    else return 1.0F - dis / maxLen;
}
</code></pre>

<p>but this for me is not enough. Because I need more complex way to match two sentences.</p>

<p>For example I want automatically tag some music, I have original song names, and i have songs with trash, like <em>super, quality,</em> years like <em>2007, 2008,</em> etc..etc.. also some files have just <a href="http://trash..thash..song_name_mp3.mp3" rel="nofollow noreferrer">http://trash..thash..song_name_mp3.mp3</a>, other are normal. I want to create an algorithm which will work just more perfect than mine now.. Maybe anyone can help me?</p>

<p>here is my current algo:</p>

<pre><code>/// &lt;summary&gt;
/// if we need to ignore this target.
/// &lt;/summary&gt;
/// &lt;param name="targetString"&gt;The target string.&lt;/param&gt;
/// &lt;returns&gt;&lt;/returns&gt;
private bool doIgnore(String targetString)
{
    if ((targetString != null) &amp;&amp; (targetString != String.Empty))
    {
        for (int i = 0; i &lt; ignoreWordsList.Length; ++i)
        {
            //* if we found ignore word or target string matching some some special cases like years (Regex).
            if (targetString == ignoreWordsList[i] || (isMatchInSpecialCases(targetString))) return true;
        }
    }

   return false;
}

/// &lt;summary&gt;
/// Removes the duplicates.
/// &lt;/summary&gt;
/// &lt;param name="list"&gt;The list.&lt;/param&gt;
private void removeDuplicates(List&lt;String&gt; list)
{
    if ((list != null) &amp;&amp; (list.Count &gt; 0))
    {
        for (int i = 0; i &lt; list.Count - 1; ++i)
        {
            if (list[i] == list[i + 1])
            {
                list.RemoveAt(i);
                --i;
            }
        }
    }
}

/// &lt;summary&gt;
/// Does the fuzzy match.
/// &lt;/summary&gt;
/// &lt;param name="targetTitle"&gt;The target title.&lt;/param&gt;
/// &lt;returns&gt;&lt;/returns&gt;
private TitleMatchResult doFuzzyMatch(String targetTitle)
{
    TitleMatchResult matchResult = null;

   if (targetTitle != null &amp;&amp; targetTitle != String.Empty)
   {
       try
       {
           //* change target title (string) to lower case.
           targetTitle = targetTitle.ToLower();

           //* scores, we will select higher score at the end.
           Dictionary&lt;Title, float&gt; scores = new Dictionary&lt;Title, float&gt;();

           //* do split special chars: '-', ' ', '.', ',', '?', '/', ':', ';', '%', '(', ')', '#', '\"', '\'', '!', '|', '^', '*', '[', ']', '{', '}', '=', '!', '+', '_'
           List&lt;String&gt; targetKeywords = new List&lt;string&gt;(targetTitle.Split(ignoreCharsList, StringSplitOptions.RemoveEmptyEntries));

          //* remove all trash from keywords, like super, quality, etc..
           targetKeywords.RemoveAll(delegate(String x) { return doIgnore(x); });
          //* sort keywords.
          targetKeywords.Sort();
        //* remove some duplicates.
        removeDuplicates(targetKeywords);

        //* go through all original titles.
        foreach (Title sourceTitle in titles)
        {
            float tempScore = 0f;
            //* split orig. title to keywords list.
            List&lt;String&gt; sourceKeywords = new List&lt;string&gt;(sourceTitle.Name.Split(ignoreCharsList, StringSplitOptions.RemoveEmptyEntries));
            sourceKeywords.Sort();
            removeDuplicates(sourceKeywords);

            //* go through all source ttl keywords.
            foreach (String keyw1 in sourceKeywords)
            {
                float max = float.MinValue;
                foreach (String keyw2 in targetKeywords)
                {
                    float currentScore = StringMatching.StringMatching.CalculateSimilarity(keyw1.ToLower(), keyw2);
                    if (currentScore &gt; max)
                    {
                        max = currentScore;
                    }
                }
                tempScore += max;
            }

            //* calculate average score.
            float averageScore = (tempScore / Math.Max(targetKeywords.Count, sourceKeywords.Count)); 

            //* if average score is bigger than minimal score and target title is not in this source title ignore list.
            if (averageScore &gt;= minimalScore &amp;&amp; !sourceTitle.doIgnore(targetTitle))
            {
                //* add score.
                scores.Add(sourceTitle, averageScore);
            }
        }

        //* choose biggest score.
        float maxi = float.MinValue;
        foreach (KeyValuePair&lt;Title, float&gt; kvp in scores)
        {
            if (kvp.Value &gt; maxi)
            {
                maxi = kvp.Value;
                matchResult = new TitleMatchResult(maxi, kvp.Key, MatchTechnique.FuzzyLogic);
            }
        }
    }
    catch { }
}
//* return result.
return matchResult;
}
</code></pre>

<p>This works normally but just in some cases, a lot of titles which should match, does not match... I think I need some kind of formula to play with weights and etc, but i can't think of one.. </p>

<p>Ideas? Suggestions? Algos?</p>

<p>by the way I already know this topic (My colleague already posted it but we cannot come with a proper solution for this problem.): 
<a href="https://stackoverflow.com/questions/49263/approximate-string-matching-algorithms">Approximate string matching algorithms</a></p>

[{'answer_id': 53531, 'author': 'Greg', 'author_id': 4123, 'author_profile': 'https://Stackoverflow.com/users/4123', 'pm_score': 3, 'selected': False, 'text': '<p>It sounds like what you want may be a longest substring match. That is, in your example, two files like</p>\n\n<p>trash..thash..song_name_mp3.mp3\nand\ngarbage..spotch..song_name_mp3.mp3</p>\n\n<p>would end up looking the same.</p>\n\n<p>You\'d need some heuristics there, of course. One thing you might try is putting the string through a soundex converter. Soundex is the "codec" used to see if things "sound" the same (as you might tell a telephone operator). It\'s more or less a rough phonetic and mispronunciation semi-proof transliteration. It is definitely poorer than edit distance, but much, much cheaper. (The official use is for names, and only uses three characters. There\'s no reason to stop there, though, just use the mapping for every character in the string. See <a href="http://en.wikipedia.org/wiki/Soundex" rel="noreferrer">wikipedia</a> for details)</p>\n\n<p>So my suggestion would be to soundex your strings, chop each one into a few length tranches (say 5, 10, 20) and then just look at clusters. Within clusters you can use something more expensive like edit distance or max substring.</p>\n'}, {'answer_id': 53539, 'author': 'Keith', 'author_id': 905, 'author_profile': 'https://Stackoverflow.com/users/905', 'pm_score': 4, 'selected': True, 'text': "<p>Your problem here may be distinguishing between noise words and useful data:</p>\n\n<ul>\n<li>Rolling_Stones.Best_of_2003.Wild_Horses.mp3</li>\n<li>Super.Quality.Wild_Horses.mp3</li>\n<li>Tori_Amos.Wild_Horses.mp3</li>\n</ul>\n\n<p>You may need to produce a dictionary of noise words to ignore. That seems clunky, but I'm not sure there's an algorithm that can distinguish between band/album names and noise.</p>\n"}, {'answer_id': 55913, 'author': 'ima', 'author_id': 5733, 'author_profile': 'https://Stackoverflow.com/users/5733', 'pm_score': 2, 'selected': False, 'text': '<p>There\'s a lot of work done on somewhat related problem of DNA sequence alignment (search for "local sequence alignment") - classic algorithm being "Needleman-Wunsch" and more complex modern ones also easy to find. The idea is - similar to Greg\'s answer - instead of identifying and comparing keywords try to find longest loosely matching substrings within long strings. </p>\n\n<p>That being sad, if the only goal is sorting music, a number of regular expressions to cover possible naming schemes would probably work better than any generic algorithm.</p>\n'}, {'answer_id': 10079256, 'author': 'Alain', 'author_id': 529618, 'author_profile': 'https://Stackoverflow.com/users/529618', 'pm_score': 4, 'selected': False, 'text': '<p>Kind of old, but It might be useful to future visitors. If you\'re already using the Levenshtein algorithm and you need to go a little better, I describe some very effective heuristics in this solution:</p>\n\n<p><a href="https://stackoverflow.com/questions/5859561/getting-the-closest-string-match/5859823#5859823">Getting the closest string match</a></p>\n\n<p>The key is that you come up with 3 or 4 (or <a href="http://en.wikipedia.org/wiki/String_metric" rel="nofollow noreferrer">more</a>) methods of gauging the similarity between your phrases (Levenshtein distance is just one method) - and then using real examples of strings you want to match as similar, you adjust the weightings and combinations of those heuristics until you get something that maximizes the number of positive matches. Then you use that formula for all future matches and you should see great results.</p>\n\n<p>If a user is involved in the process, it\'s also best if you provide an interface which allows the user to see additional matches that rank highly in similarity in case they disagree with the first choice.</p>\n\n<p>Here\'s an excerpt from the linked answer. If you end up wanting to use any of this code as is, I apologize in advance for having to convert VBA into C#.</p>\n\n<hr>\n\n<p>Simple, speedy, and a very useful metric. Using this, I created two separate metrics for evaluating the similarity of two strings. One I call "valuePhrase" and one I call "valueWords". valuePhrase is just the Levenshtein distance between the two phrases, and valueWords splits the string into individual words, based on delimiters such as spaces, dashes, and anything else you\'d like, and compares each word to each other word, summing up the shortest Levenshtein distance connecting any two words. Essentially, it measures whether the information in one \'phrase\' is really contained in another, just as a word-wise permutation. I spent a few days as a side project coming up with the most efficient way possible of splitting a string based on delimiters.</p>\n\n<p>valueWords, valuePhrase, and Split function:</p>\n\n<pre><code>Public Function valuePhrase#(ByRef S1$, ByRef S2$)\n    valuePhrase = LevenshteinDistance(S1, S2)\nEnd Function\n\nPublic Function valueWords#(ByRef S1$, ByRef S2$)\n    Dim wordsS1$(), wordsS2$()\n    wordsS1 = SplitMultiDelims(S1, " _-")\n    wordsS2 = SplitMultiDelims(S2, " _-")\n    Dim word1%, word2%, thisD#, wordbest#\n    Dim wordsTotal#\n    For word1 = LBound(wordsS1) To UBound(wordsS1)\n        wordbest = Len(S2)\n        For word2 = LBound(wordsS2) To UBound(wordsS2)\n            thisD = LevenshteinDistance(wordsS1(word1), wordsS2(word2))\n            If thisD &lt; wordbest Then wordbest = thisD\n            If thisD = 0 Then GoTo foundbest\n        Next word2\nfoundbest:\n        wordsTotal = wordsTotal + wordbest\n    Next word1\n    valueWords = wordsTotal\nEnd Function\n\n\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\n\' SplitMultiDelims\n\' This function splits Text into an array of substrings, each substring\n\' delimited by any character in DelimChars. Only a single character\n\' may be a delimiter between two substrings, but DelimChars may\n\' contain any number of delimiter characters. It returns a single element\n\' array containing all of text if DelimChars is empty, or a 1 or greater\n\' element array if the Text is successfully split into substrings.\n\' If IgnoreConsecutiveDelimiters is true, empty array elements will not occur.\n\' If Limit greater than 0, the function will only split Text into \'Limit\'\n\' array elements or less. The last element will contain the rest of Text.\n\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\nFunction SplitMultiDelims(ByRef Text As String, ByRef DelimChars As String, _\n        Optional ByVal IgnoreConsecutiveDelimiters As Boolean = False, _\n        Optional ByVal Limit As Long = -1) As String()\n    Dim ElemStart As Long, N As Long, M As Long, Elements As Long\n    Dim lDelims As Long, lText As Long\n    Dim Arr() As String\n\n    lText = Len(Text)\n    lDelims = Len(DelimChars)\n    If lDelims = 0 Or lText = 0 Or Limit = 1 Then\n        ReDim Arr(0 To 0)\n        Arr(0) = Text\n        SplitMultiDelims = Arr\n        Exit Function\n    End If\n    ReDim Arr(0 To IIf(Limit = -1, lText - 1, Limit))\n\n    Elements = 0: ElemStart = 1\n    For N = 1 To lText\n        If InStr(DelimChars, Mid(Text, N, 1)) Then\n            Arr(Elements) = Mid(Text, ElemStart, N - ElemStart)\n            If IgnoreConsecutiveDelimiters Then\n                If Len(Arr(Elements)) &gt; 0 Then Elements = Elements + 1\n            Else\n                Elements = Elements + 1\n            End If\n            ElemStart = N + 1\n            If Elements + 1 = Limit Then Exit For\n        End If\n    Next N\n    \'Get the last token terminated by the end of the string into the array\n    If ElemStart &lt;= lText Then Arr(Elements) = Mid(Text, ElemStart)\n    \'Since the end of string counts as the terminating delimiter, if the last character\n    \'was also a delimiter, we treat the two as consecutive, and so ignore the last elemnent\n    If IgnoreConsecutiveDelimiters Then If Len(Arr(Elements)) = 0 Then Elements = Elements - 1\n\n    ReDim Preserve Arr(0 To Elements) \'Chop off unused array elements\n    SplitMultiDelims = Arr\nEnd Function\n</code></pre>\n\n<p><strong>Measures of Similarity</strong></p>\n\n<p>Using these two metrics, and a third which simply computes the distance between two strings, I have a series of variables which I can run an optimization algorithm to achieve the greatest number of matches. Fuzzy string matching is, itself, a fuzzy science, and so by creating linearly independent metrics for measuring string similarity, and having a known set of strings we wish to match to each other, we can find the parameters that, for our specific styles of strings, give the best fuzzy match results.</p>\n\n<p>Initially, the goal of the metric was to have a low search value for for an exact match, and increasing search values for increasingly permuted measures. In an impractical case, this was fairly easy to define using a set of well defined permutations, and engineering the final formula such that they had increasing search values results as desired.</p>\n\n<p><img src="https://i.stack.imgur.com/eGCtC.png" alt="enter image description here"></p>\n\n<p>As you can see, the last two metrics, which are fuzzy string matching metrics, already have a natural tendency to give low scores to strings that are meant to match (down the diagonal). This is very good. </p>\n\n<p><strong>Application</strong>\nTo allow the optimization of fuzzy matching, I weight each metric. As such, every application of fuzzy string match can weight the parameters differently. The formula that defines the final score is a simply combination of the metrics and their weights:</p>\n\n<pre><code>value = Min(phraseWeight*phraseValue, wordsWeight*wordsValue)*minWeight + \n        Max(phraseWeight*phraseValue, wordsWeight*wordsValue)*maxWeight + lengthWeight*lengthValue\n</code></pre>\n\n<p>Using an optimization algorithm (neural network is best here because it is a discrete, multi-dimentional problem), the goal is now to maximize the number of matches. I created a function that detects the number of correct matches of each set to each other, as can be seen in this final screenshot. A column or row gets a point if the lowest score is assigned the the string that was meant to be matched, and partial points are given if there is a tie for the lowest score, and the correct match is among the tied matched strings. I then optimized it. You can see that a green cell is the column that best matches the current row, and a blue square around the cell is the row that best matches the current column. The score in the bottom corner is roughly the number of successful matches and this is what we tell our optimization problem to maximize. </p>\n\n<p><img src="https://i.stack.imgur.com/hsMtp.png" alt="enter image description here"></p>\n'}, {'answer_id': 55732425, 'author': 'Ricardo stands with Ukraine', 'author_id': 364568, 'author_profile': 'https://Stackoverflow.com/users/364568', 'pm_score': 0, 'selected': False, 'text': '<p>There is a <a href="https://github.com/kdjones/fuzzystring" rel="nofollow noreferrer">GitHub repo</a> implementing several methods.</p>\n'}]
['https://Stackoverflow.com/questions/53480', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5369/']