My C# .NET program uses:
DirInfo.EnumerateFiles(Program.sSourceFilePattern, SearchOption.TopDirectoryOnly)
to search a folder for filenames matching 'sSourceFilePattern'. This search pattern is user supplied and I want to validate the pattern before executing the DirInfo.
I found a regex pattern at How do I check if a given string is a legal / valid file name under Windows? that I lifted and modified to permit wildcard characters * and ?:
sPattern = @"^(?!^(PRN|AUX|CLOCK\$|NUL|CON|COM\d|LPT\d|\..*)(\..+)?$)[^\x00-\x1f\\:\"";|/]+$";
This pattern works fairly well, but will still permit nonsensical patterns involving multiple wildcard characters. For example, this will permit invalid search strings like:
abc*123.txt
abc*???.txt
*abc.txt
I think that refining this further will involve more than regexs, because it requires applying logic about where the asterisks may occur and what may follow them, whether it's before of after the period (separator), etc.
Nevertheless, I would appreciate any suggestions for improving this regex to catch more of the common errors. Thanks in advance!