Given the requirements specified in the previously cited MSDN documentation, the following regex should do a pretty good job:
public static boolean isValidName(String text)
{
Pattern pattern = Pattern.compile(
"# Match a valid Windows filename (unspecified file system).
" +
"^ # Anchor to start of string.
" +
"(?! # Assert filename is not: CON, PRN,
" +
" (?: # AUX, NUL, COM1, COM2, COM3, COM4,
" +
" CON|PRN|AUX|NUL| # COM5, COM6, COM7, COM8, COM9,
" +
" COM[1-9]|LPT[1-9] # LPT1, LPT2, LPT3, LPT4, LPT5,
" +
" ) # LPT6, LPT7, LPT8, and LPT9...
" +
" (?:\.[^.]*)? # followed by optional extension
" +
" $ # and end of string
" +
") # End negative lookahead assertion.
" +
"[^<>:"/\\|?*\x00-\x1F]* # Zero or more valid filename chars.
" +
"[^<>:"/\\|?*\x00-\x1F\ .] # Last char is not a space or dot.
" +
"$ # Anchor to end of string. ",
Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE | Pattern.COMMENTS);
Matcher matcher = pattern.matcher(text);
boolean isMatch = matcher.matches();
return isMatch;
}
Note that this regex does not impose any limit on the length of the filename, but a real filename may be limited to 260 or 32767 chars depending on the platform.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…