【发布时间】: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