【问题标题】:converting Wildcard to Regex将通配符转换为正则表达式
【发布时间】:2017-12-16 09:39:17
【问题描述】:

我是 MVC 的新手,我想对数据库执行通配符 (*, ?) 搜索。这就是我使用正则表达式所做的:

控制器:

using System.Linq;
using System.Text.RegularExpressions;
using System.Web.Mvc;
using WebApplication1.Models;


namespace WebApplication1.Controllers
{
    public class HomeController : Controller
    {

        CrossWord_dbEntities db = new CrossWord_dbEntities();

        public ActionResult Index(string searching)
        {
            if (searching == null)
            {
                searching = "*";
            }
            string regEx = WildcardToRegex(searching);
            return View(db.tbl_values.ToList().Where(x => Regex.IsMatch(x.Name, regEx, RegexOptions.Singleline)));            
        }

        public static string WildcardToRegex(string pattern)
        {
            return "^" + Regex.Escape(pattern).
            Replace("\\*", ".*").
            Replace("\\?", ".") + "$";
        }
    }
}

查看:

@model IEnumerable<WebApplication1.Models.tbl_values>

<br /><br />
@using (Html.BeginForm("Index", "Home", FormMethod.Get))
{
@Html.TextBox("searching") <input type="submit" value="Search" />
}

<table class="table table-striped">
    <thead>
        <tr>
            <th>Results</th>
        </tr>
    </thead>
    <tbody>
        @if (Model.Count() == 0)
        {
            <tr>
                <td colspan="3" style="color:red">
                    No Result 
                </td>
            </tr>
        }
        else
        {
            foreach (var item in Model)
            {
                <tr>
                    <td>
                        @item.Name
                    </td>
                </tr>
            }
        }

    </tbody>

</table>

我的数据库中有三条记录:Hello, Hero, Shalom

当我输入“H*”时,我得到结果:你好,英雄——这很好用 但是当我输入“*lom”时,我得到的是“No Result”而不是“Shalom” 或者当我输入“地狱?”我得到“没有结果”而不是“你好”

我做错了什么?

【问题讨论】:

    标签: regex asp.net-mvc wildcard


    【解决方案1】:

    你可以使用以下

    Expression<Func<tbl_value, bool>> query = m =>
    SqlFunctions.PatIndex(searching.ToLower().Replace("*", "%"), m.Name.ToLower()) > 0;
    
    var details = db.tbl_values.Where(query);
    

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 2012-11-28
      • 1970-01-01
      • 2012-09-23
      • 1970-01-01
      • 2014-05-19
      • 1970-01-01
      • 2019-06-23
      • 2011-10-02
      • 2016-04-02
      相关资源
      最近更新 更多