使用百分比的通配符搜索

时间:2013-10-21 23:21:23

标签: c# regex wildcard

我在linqpad中有以下示例代码。复制/粘贴到linqpad并选择语言c#语句来运行它。

目前'AB%C'仅匹配AB C,我希望%匹配零个或多个字符,如SQL中。

// Define Stock Items
List<StockItem> stockItems = new List<StockItem>();

stockItems.Add(new StockItem{
Id = 0,
Code = "444B",
Description = "AB C"
});

stockItems.Add(new StockItem{
Id = 0,
Code = "11221",
Description = "ABC"
});

// Regex Search of Stock Items
string searchString = "AB%C";
string regexSearch = searchString
                 .Replace("*", ".+")
                 .Replace("%", ".+")
                 .Replace("#", "\\d")
                 .Replace("@", "[a-zA-Z]")
                 .Replace("?", "\\w");
Regex regex = new Regex(regexSearch);

List<StockItem> results;
results = stockItems.Where(s => regex.IsMatch(s.Description)).ToList();

results.Dump();

} // Bracket defines end of logic so we can declare classes next

// StockItem Class
internal class StockItem
{ 
public int Id {get; set;}
public string Code {get; set;}
public string Description {get; set;}
// } Don't close class for linqpad!

我从this stackoverflow thread

获得正则表达式

1 个答案:

答案 0 :(得分:3)

+表示“一个或多个”,您需要*而不是“零或更多”:

.Replace("%", ".*")