2

如果搜索文本和列表中的项目大小写相同(小写/大写),我有以下代码有效。如果有混合外壳,则它不起作用。我们怎样才能使它不区分大小写的搜索。

var text = "c";
var myStrings = new List<string>() { "Aa", "ACB", "cc" };
var regEx = new System.Text.RegularExpressions.Regex(text);
var results = myStrings
        .Where<string>(item => regEx.IsMatch(item))
        .ToList<string>();

编辑 :

我需要以不区分大小写的方式传递该字符串,我该怎么做...

  public ActionResult GetItems(string text)
  {
        ContextObject contextObject = new ContextObject();          
        TransactionHistory transactionhistory = new TransactionHistory();
        System.Text.RegularExpressions.Regex regEx = new System.Text.RegularExpressions.Regex(text, RegexOptions.IgnoreCase);
        var items = transactionhistory.GetItems(contextObject, text);

        return Json(items, JsonRequestBehavior.AllowGet);                     
  }
4

3 回答 3

5

尝试像这样声明您的正则表达式

Regex regEx = new Regex(text, RegexOptions.IgnoreCase);
于 2013-08-29T05:53:27.160 回答
1

您需要使用采用RegexOptions.IgnoreCase的重载

例子

 RegexOptions options = RegexOptions.IgnoreCase | RegexOptions.Compiled;
 System.Text.RegularExpressions.Regex regEx = new System.Text.RegularExpressions.Regex(text, options);

编辑:

RegexOptions options = RegexOptions.IgnoreCase | RegexOptions.Compiled;            
var text = "c";
var myStrings = new List<string>() { "Aa", "ACB", "cc" };
var regEx = new System.Text.RegularExpressions.Regex(text, options);
var results = myStrings
             .Where<string>(item => regEx.IsMatch(item))
             .ToList<string>();

//you will have 2 items in results
foreach(string s in results)
{
    GetItems(s);
}
于 2013-08-29T05:54:04.990 回答
0

根据您的代码,为什么要使用正则表达式?我只会使用带有复杂文本模式的正则表达式。在这种情况下,使用 string.IndexOf() 更容易,如

var text = "c";
var myStrings = new List<string>() { "Aa", "ACB", "cc" };
var results = myStrings
    .Where(item => item.IndexOf(text, StringComparison.CurrentCultureIgnoreCase) >= 0)
    .ToList();

我已经删除了字符串在 where 和 toList 中的显式使用,因为它是默认应用的。

于 2013-08-29T06:39:07.660 回答