将搜索字符串转换为FullText兼容的搜索字符串?

时间:2010-05-21 00:48:37

标签: c# sql-server search full-text-search

我正在使用MSSQL 2008的全文搜索引擎,它需要一个像这样的搜索字符串:

("keyword1" AND "keyword2*" OR "keyword3")

我的用户输入的内容如下:

engine 2009
"san francisco"     hotel december xyz
stuff* "in miami"   1234
something or "something else"

我正在尝试将这些转换为全文引擎兼容的字符串,如下所示:

("engine" AND "2009")
("san francisco" AND "hotel" AND "december" AND "xyz")
("stuff*" "in miami" "1234")
("something" OR "something else")

我有一个非常困难的时间,尝试使用计数引号,空格和插入等,但我的代码看起来像是可怕的呕吐物。

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:6)

你走了:

class Program {
    static void Main(string[] args) {
        // setup some test expressions
        List<string> searchExpressions = new List<string>(new string[] { 
            "engine 2009", 
            "\"san francisco\"     hotel december xyz", 
            "stuff* \"in miami\"   1234 ", 
            "something or \"something else\""
        });

        // display and parse each expression
        foreach (string searchExpression in searchExpressions) {
            Console.WriteLine(string.Concat(
                "User Input: ", searchExpression, 
                "\r\n\tSql Expression: ", ParseSearchExpression(searchExpression), 
                "\r\n"));
        }

        Console.ReadLine();

    }

private static string ParseSearchExpression(string searchExpression) {
    // replace all 'spacecharacters' that exists within quotes with character 0
    string temp = Regex.Replace(searchExpression, @"""[^""]+""", (MatchEvaluator)delegate(Match m) {
        return Regex.Replace(m.Value, @"[\s]", "\x00");
    });

    // split string on any spacecharacter (thus: quoted items will not be splitted)
    string[] tokens = Regex.Split(temp, @"[""\s]+", RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);

    // generate result
    StringBuilder result = new StringBuilder();
    string tokenLast = string.Empty;
    foreach (string token in tokens) {
        if (token.Length > 0) {
            if ((token.Length > 0) && (!token.Equals("AND", StringComparison.OrdinalIgnoreCase))) {
                if (result.Length > 0) {
                    result.Append(tokenLast.Equals("OR", StringComparison.OrdinalIgnoreCase) ? " OR " : " AND ");
                }
                result.Append("\"").Append(token.Replace("\"", "\"\"").Replace("\x00", " ")).Append("\"");
            }
            tokenLast = token;
        }
    }
    if (result.Length > 0) {
        result.Insert(0, "(").Append(")");
    }

    return result.ToString();
}
}