如何使用正则表达式和匹配来搜索多个字段中的多个搜索字词?

时间:2016-01-14 11:56:23

标签: .net regex

我有一个Person对象数组。我想在多个字段中搜索多个搜索词。我成功将多个searchterm搜索到一个字段中。但我不知道如何克服在多个字段中搜索多个搜索词。我试过如下。

using System.Text.RegularExpressions;

...

Regex searchTerm = new Regex(@"(daniels|john|jack|freeman)"); //multiple search terms

var queryMatchingFiles =
    from a in list
    let matches = searchTerm.Matches(a.Name)
    //let matches = searchTerm.Matches(a.Surname) it gives an error
    where matches.Count > 0
    select new
    {
        a
    };

 ...

class Person
 {
     private string name;
     private string surname;
     private string tc;

     public Person(string name, string surname, string tc)
     {
         this.name = name;
         this.surname = surname;
         this.tc = tc;
     }

     public string Name
     {
         get { return name; }
         set { name = value; }
     }

     public string Surname
     {
         get { return surname; }
         set { surname = value; }
     }

     public string Tc
     {
         get { return tc; }
         set { tc = value; }
     }
 }

如何解决问题?

1 个答案:

答案 0 :(得分:1)

您可以使用Regex.IsMatch检查正则表达式模式是否与给定字段匹配,并使用OR逻辑运算符确保在任何字段匹配时返回a

var list = new List<Person> { new Person { Name = "daniels", Surname ="koln" },
           new Person { Name = "jon", Surname ="freeman" }};
var searchTerm = new System.Text.RegularExpressions.Regex(@"(daniels|john|jack|freeman)");
var queryMatchingFiles =
      (from a in list
       where (searchTerm.IsMatch(a.Name) || searchTerm.IsMatch(a.Surname)) // Add conditions here
       select new
       {
          a
       }).ToList();

enter image description here

根据您的编辑,使用

where (searchTerm.IsMatch(a.Name) || 
       searchTerm.IsMatch(a.Surname) ||
       searchTerm.IsMatch(a.Tc))