0

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

目前 '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!

我从这个stackoverflow线程获得了正则表达式

4

1 回答 1

3

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

.Replace("%", ".*")
于 2013-10-21T23:30:03.480 回答