是否存在内置的通配符匹配?

时间:2018-03-16 15:11:31

标签: c# asp.net-core

我有一个字符串列表。我需要接受用户提供的通配符字符串列表,并返回所有匹配项(只需要支持*运算符)。我知道这可以用正则表达式来完成,我只是担心它太过分了,会让我接触到一些潜在的恶意攻击。

从我的搜索中我发现了一些VisualBasic这样做的东西,只是在核心中似乎没有支持它。我还发现Directory.GetFiles()只使用文件的实际目录而不是列表来执行此操作。

是否有一些构建方式可以做到这一点?我只是不想担心重新发明轮子和处理安全问题。

实施例

files = ["foo\bar", "foo\foo", "bar\foo", "test"]
patterns = ["test", "foo\*"]

matches = ["foo\bar", "foo\foo", "test"]

除了*

,我不需要任何特殊的操作符

1 个答案:

答案 0 :(得分:0)

我担心在c#中没有内置匹配通配符的方法。

然而,你可以模仿通配符' *'匹配这样的东西。

// Since you only need '*' wildcard functionality, separate the wildcard
// into segments to match against the list items

public IEnumerable<string> GetWildcardSegments(string wildcard)
{
    return wildcard.Split('*');
}

public List<string> FilterListWithWildcard(IEnumerable<string> list, string wildcard)
{
    List<string> result = new List<string>();
    foreach(string listItem in list)
    {
        bool matchFailed = false;
        foreach(string segment in GetWildcardSegments(wildcard))
        {
            if(!listItem.Contains(segment))
            {
                matchFailed = true;
                break;
            }
        }
        if(!matchFailed)
        {
            result.Add(listItem);
        }
    }
    return result;
}