Fork me on GitHub

Programming Design Notes

LINQ 配合 Regular Expression

| Comments

LINQ 是 Microsoft .Net 的產物
擁有靈活的搜尋功能
如果將 LINQ 配合 Regular Expression
更加方便和更有彈性

以下的例子:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace LINQTest
{
class Program
{
static void Main(string[] args)
{
string[] name =
{ "Ann", "Addison", "Peter", "John",
"Lawrence", "Mary", "Barclay", "Buckley",
"Dawn", "Leslie", "Queenie", "Palma",
"Fatima", "Unaiza", "Karida", "Zarifa"
};
Regex pattern = new Regex("^[laz]\\w*[ea]$", RegexOptions.IgnoreCase);
IEnumerable<string> nameList = name.Where(n => pattern.IsMatch(n));
foreach (string filteredName in nameList)
Console.WriteLine(filteredName);
Console.ReadLine();
}
}
}

例如我想將 l, a, z 開頭和 e, a 結尾的名稱找出來
先設定好 Regular Expression Pattern

new Regex("^[laz]\\w*[ea]$", RegexOptions.IgnoreCase);

RegexOptions.IgnoreCase 作用是不理英文字母是大寫還是小寫

IEnumerable<string> nameList = name.Where(n => pattern.IsMatch(n));

如果條件附合便將 name 放到 nameList 內

例子的執行結果是
Lawrence
Leslie
Zarifa

相關書籍: Pro LINQ: Language Integrated Query in C# 2008 (Windows.Net)LINQ Unleashed: for C#Programming Microsoft® LINQ (PRO-Developer)