How to determine if a File Matches a File Mask?

后端 未结 13 1642
清歌不尽
清歌不尽 2020-12-14 07:14

I need to decide whether file name fits to file mask. The file mask could contain * or ? characters. Is there any simple solution for this?

bool bFits = Fits         


        
13条回答
  •  离开以前
    2020-12-14 07:48

    Fastest version of the previously proposed function:

        public static bool FitsMasks(string filePath, params string[] fileMasks)
                // or
        public static Regex FileMasksToRegex(params string[] fileMasks)
        {
            if (!_maskRegexes.ContainsKey(fileMasks))
            {
                StringBuilder sb = new StringBuilder("^");
                bool first = true;
                foreach (string fileMask in fileMasks)
                {
                    if(first) first =false; else sb.Append("|");
                    sb.Append('(');
                    foreach (char c in fileMask)
                    {
                        switch (c)
                        {
                            case '*': sb.Append(@".*"); break;
                            case '?': sb.Append(@"."); break;
                            default:
                                    sb.Append(Regex.Escape(c.ToString()));
                                break;
                        }
                    }
                    sb.Append(')');
                }
                sb.Append("$");
                _maskRegexes[fileMasks] = new Regex(sb.ToString(), RegexOptions.IgnoreCase);
            }
            return _maskRegexes[fileMasks].IsMatch(filePath);
                        // or
            return _maskRegexes[fileMasks];
        }
        static readonly Dictionary _maskRegexes = new Dictionary(/*unordered string[] comparer*/);
    

    Notes:

    1. Re-using Regex objects.
    2. Using StringBuilder to optimize Regex creation (multiple .Replace() calls are slow).
    3. Multiple masks, combined with OR.
    4. Another version returning the Regex.

提交回复
热议问题