【问题标题】:Java reg exp match pattern against file names针对文件名的 Java 正则表达式匹配模式
【发布时间】:2015-05-04 20:27:46
【问题描述】:
Pattern.compile("# Match a valid Windows filename (unspecified file system).    \n"
+ "^   # Anchor to start of string. \n"
+ "(?! # Assert filename is not: CON, PRN, \n"
+ "(?: # AUX, NUL, COM1, COM2, COM3, COM4, \n"
+ "CON|PRN|AUX|NUL| # COM5, COM6, COM7, COM8, COM9, \n"
+ "COM[1-9]|LPT[1-9]  # LPT1, LPT2, LPT3, LPT4, LPT5, \n"
+ " )  # LPT6, LPT7, LPT8, and LPT9... \n"
+ " +([.]txt) # followed by .txt    \n"
 "  $  # and end of string \n"
+ ")   # End negative lookahead assertion. \n"
+ "[^<>:\"/\\\\|?*\\x00-\\x1F.]*  # Zero or more valid filename chars.\n"
+ "[^<>:\"/\\\\|?*\\x00-\\x1F\\ .]  # Last char is not a space or dot.  \n"
+ "  +([.]txt)   # followed by .txt    \n"
+ "$   # Anchor to end of string.            ",
Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE| Pattern.COMMENTS);

我正在尝试使用此模式检查来验证文件名(仅.txt 文本文件),但此模式不允许包含句点的文件名,例如:"a.b"。有人建议我缺少什么吗?

【问题讨论】:

  • 你能修复可能应该被格式化为代码的巨型块吗?有助于提高可读性。
  • 我刚刚编辑了它,对不起@BenKnoble
  • 没问题;我不知道如何考虑正则表达式,但这样做的人会欣赏这一点。

标签: java regex


【解决方案1】:

我认为用"# Zero or more valid filename chars." 注释的最后第四行应该没有点(.):

+ "[^<>:\"/\\\\|?*\\x00-\\x1F]*  # Zero or more valid filename chars.\n"

(而且我不确定倒数第二行中的量词 + 是什么意思)。

另见Validate a file name on Windows

【讨论】:

    猜你喜欢
    • 2016-04-24
    • 2016-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多