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

前端之家收集整理的这篇文章主要介绍了c# – 将搜索字符串转换为FullText兼容的搜索字符串?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用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")

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

有人可以帮忙吗?

解决方法

干得好:
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();
}
}
原文链接:https://www.f2er.com/csharp/100780.html

猜你在找的C#相关文章