Пример #1
0
        public static double ScoreMatches(string txt, string keyword)
        {
            int numMatches, result;
            // find whole word matches

            //MK: you can't just put the keyword(s) they searched for straight into a regex - characters need to be escaped first
            Regex cleanKeywords   = new Regex("([\\[^$.|?*+()])");
            var   keywordForRegex = cleanKeywords.Replace(keyword, "\\$1");

            // MN - todo: escape any bad chars - needs testing
            keywordForRegex = Fmt.RegExEscape(keyword);

            Regex rx = new Regex("\\b" + keywordForRegex + "\\b", RegexOptions.IgnoreCase);

            //var matchArray = new String("" + txt).match(re)
            MatchCollection matchArray = rx.Matches(txt);

            if (matchArray.Count == 0)
            {
                numMatches = 0;
            }
            else
            {
                numMatches = matchArray.Count;                //.VB.length
            }
            result = 0;
            if (numMatches == 0)
            {
                result += 0;
            }
            else if (numMatches == 1)
            {
                result += 5;
            }
            else if (numMatches == 2)
            {
                result += 7;
            }
            else if (numMatches < 5)
            {
                result += 8;
            }
            else
            {
                result += 9;
            }

            if (numMatches == 0)
            {
                // find partial word matches
                rx = new Regex(keywordForRegex, RegexOptions.IgnoreCase);
                //matchArray = new String("" + txt).match(re)
                matchArray = rx.Matches(txt);
                numMatches = matchArray.Count;                 //.VB.length

                if (numMatches == 0)
                {
                    result += 0;
                }
                else if (numMatches == 1)
                {
                    result += 1;
                }
                else if (numMatches == 2)
                {
                    result += 2;
                }
                else if (numMatches < 5)
                {
                    result += 3;
                }
                else
                {
                    result += 4;
                }
            }

            return(result);
        }