0

全文検索を使用した検索プロシージャ(つまり、プロシージャの外部で一致を再現するのは困難です)は、次のように、内部で一致した文字列を強調表示する行を返します。

"i have been <em>match</em>ed"
"a <em>match</em> will happen in the word <em>match</em>"
"some random words including the word <em>match</em> here"

文字列の最初のx文字を取得する必要がありますが、内部のhtmlタグでいくつかの問題が発生しています。

好き:

"i have been <em>mat</em>..." -> first 15 characters
"a <em>match</em> will happen in the word <em>m</em>..." -> first 33 characters
"some rando..." -> first 10 characters

他にも使ってみましたが、大きなスパゲッティになってしまいました。

任意のヒント?

4

2 に答える 2

1

いくつかの状態を含む単純なパーサーを作成することをお勧めします-、、InTextInOpeningTag頭に浮かぶInClosingTagいくつかの例です。

文字をループして、InTextそれらの文字だけを数えているかどうかを確認します...制限に達したら、それ以上テキストを追加せず、開始タグと終了タグの間にある場合は、終了タグを追加するだけです。

私が何について話しているのかわからない場合は、 HTML Agility Packのソースコードを見てください(Parseメソッドを探してください)。

于 2012-06-22T19:22:48.353 に答える
1

<em>これは、タグしかないことに基づいて、あなたが望むことをするはずです。

using System;
using System.Collections.Generic;
using System.Text;

namespace Test
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var dbResults = GetMatches();
            var firstLine = HtmlSubstring(dbResults[0], 0, 15);
            Console.WriteLine(firstLine);
            var secondLine = HtmlSubstring(dbResults[1], 0, 33);
            Console.WriteLine(secondLine);
            var thirdLine = HtmlSubstring(dbResults[2], 0, 10);
            Console.WriteLine(thirdLine);

            Console.Read();
        }

        private static List<string> GetMatches()
        {
            return new List<string>
            {
                "i have been <em>match</em>ed"
                ,"a <em>match</em> will happen in the word <em>match</em>"
                , "some random words including the word <em>match</em> here"
            };
        }

        private static string HtmlSubstring(string mainString, int start, int length = int.MaxValue)
        {
            StringBuilder substringResult = new StringBuilder(mainString.Replace("</em>", "").Replace("<em>", "").Substring(start, length));

            // Get indexes between start and (start + length) that need highlighting.
            int matchIndex = mainString.IndexOf("<em>", start);
            while (matchIndex > 0 && matchIndex < (substringResult.Length - start))
            {
                int matchIndexConverted = matchIndex - start;
                int matchEndIndex = mainString.IndexOf("</em>", matchIndex) - start;

                substringResult.Insert(matchIndexConverted, "<em>");
                substringResult.Insert(Math.Min(substringResult.Length, matchEndIndex), "</em>");

                matchIndex = mainString.IndexOf("<em>", matchIndex + 1);
            }

            return substringResult.ToString();
        }
    }
}
于 2012-06-22T21:32:06.400 に答える