将Wildcard转换为Regex

问题描述 投票:1回答:1

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

控制器:

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”时我得到“没有结果”而不是“Shalom”或当我输入“地狱?”我得到“没有结果”而不是“你好”

我做错了什么?

谢谢

regex asp.net-mvc wildcard
1个回答
0
投票

您可以使用以下内容

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

var details = db.tbl_values.Where(query);

希望对你有帮助

© www.soinside.com 2019 - 2024. All rights reserved.