【问题标题】:C# LINQ: how to handle wildcard search?C# LINQ:如何处理通配符搜索?
【发布时间】:2013-09-15 15:29:15
【问题描述】:

我需要这样的搜索功能: 该函数接受具有多种类型通配符的所有字符串:

* or % >>> can replace one or more characters
# >>> used to replace a number
@ >>> used to replace an alphabet
? >>> used to replace a character (can be both number and alphabet)

据我所知,在 LINQ 中有 3 个函数用于搜索字符串:StartsWith、EndsWith 和 Contains。在 SQL 查询中,LIKE 有 2 种类型:% 表示一个或多个字符,_ 表示仅一个字符。 那么,我该如何解决这个问题呢?

非常感谢

【问题讨论】:

  • 我需要一个这样的搜索功能那么到目前为止你已经尝试了什么呢?
  • 您能提供一些示例数据吗?

标签: c# linq wildcard


【解决方案1】:

您可以使用正则表达式并将通配符替换为正则表达式。这是一个例子。

    IEnumerable<string> Search(IEnumerable<string> data, string q)
    {
        string regexSearch = q
            .Replace("*", ".+")
            .Replace("%", ".+")
            .Replace("#", "\\d")
            .Replace("@", "[a-zA-Z]")
            .Replace("?", "\\w");

        Regex regex = new Regex(regexSearch);

        return data
            .Where(s => regex.IsMatch(s));
    }

【讨论】:

    猜你喜欢
    • 2021-11-25
    • 2010-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-07
    • 2011-03-13
    • 2013-05-02
    相关资源
    最近更新 更多