How to determine if a File Matches a File Mask?

后端 未结 13 1653
清歌不尽
清歌不尽 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:24

    None of these answers quite seem to do the trick, and msorens's is needlessly complex. This one should work just fine:

    public static Boolean Fits(string sFileName, string sFileMask)
    {
        String convertedMask = "^" + Regex.Escape(sFileMask).Replace("\\*", ".*").Replace("\\?", ".") + "$";
        Regex regexMask = new Regex(convertedMask, RegexOptions.IgnoreCase);
        return regexMask.IsMatch(sFileName)
    }
    

    This makes sure possible regex chars in the mask are escaped, replaces the \* and \?, and surrounds it all by ^ and $ to mark the boundaries.

    Of course, in most situations, it's far more useful to simply make this into a FileMaskToRegex tool function which returns the Regex object, so you just got it once and can then make a loop in which you check all strings from your files list on it.

    public static Regex FileMaskToRegex(string sFileMask)
    {
        String convertedMask = "^" + Regex.Escape(sFileMask).Replace("\\*", ".*").Replace("\\?", ".") + "$";
        return new Regex(convertedMask, RegexOptions.IgnoreCase);
    }
    

提交回复
热议问题