如何比較多個字符串與模式?將字符串與C中的模式進行匹配#
值:
var items = new List<string> {"item1", "item2", "item123", "new_item123"};
模式:
"%item1%" - I receive this option with an external system
預期的結果: 「物品1」, 「item123」, 「new_item123」
我們使用實體框架在數據庫中搜索數據。
如何比較多個字符串與模式?將字符串與C中的模式進行匹配#
值:
var items = new List<string> {"item1", "item2", "item123", "new_item123"};
模式:
"%item1%" - I receive this option with an external system
預期的結果: 「物品1」, 「item123」, 「new_item123」
我們使用實體框架在數據庫中搜索數據。
雖然你很可能使用正則表達式:
var pattern = new Regex("/item1/");
var items = new List<string> {"item1", "item2"};
var matches = items.Where(pattern.IsMatch);
爲什麼不只有:
var items = new List<string> {"item1", "item2"};
var matches = items.Where(item => item.Contains("item1"));
如果你真的想用一個RegEx
做到這一點,你可以用這個:
Regex r = new Regex("^item1$");
var result = items.Where(x => r.IsMatch(x)).ToList();
代碼的第一部分將不會編譯(正則表達式未聲明) – 2014-10-12 12:05:22
@FlatEric哎呀,對,謝謝。 – nvoigt 2014-10-12 12:06:11
@nvoigt,謝謝 – Pavel 2014-10-12 12:15:03