2

I have a list of strings. I need to accept a list of wildcard strings provided by the user, and return all matches (just need to support * operator). I know this can be done with Regex, i'm just afraid that it's overkill and will open me up to some potential malicious attacks.

From my searching i've found some VisualBasic stuff that does this, only it doesn't seem to be supported in core. I've also found that Directory.GetFiles() does this, only with an actual directory of files instead of just a list.

Is there some build in way of doing this? I just don't want to worry about reinventing the wheel and handling security.

EXAMPLES

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

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

I don't need any special operator except *

user3715648
  • 1,498
  • 3
  • 16
  • 25

1 Answers1

0

I'm afraid there's no built in way to match wildcards in c#.

You can however mimic wildcard '*' matching with something like this.

// 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;
}
babu646
  • 989
  • 10
  • 22
  • There's a number of issues with this code. First, by splitting on the asterisk, you're going to end up with empty strings in your list if the asterisk appears at the start or end (unless you use `StringSplitOptions.RemoveEmptyEntries`, which you aren't using). Second, you're checking only if string contains the wildcard segment, which is not the correct logic if the wildcard is at the beginning or the end only. In such cases, it should only match if the string starts or ends with the wildcard. – Chris Pratt Mar 16 '18 at 15:57