【问题标题】:Regex to catch all files but those starting with "."正则表达式捕获所有文件,但以“。”开头的文件除外。
【发布时间】:2011-02-23 22:25:20
【问题描述】:

在内容混合的目录中如:

.afile
.anotherfile
bfile.file
bnotherfile.file
.afolder/
.anotherfolder/
bfolder/
bnotherfolder/

您将如何捕获所有. 开头的文件(不是目录)?
我尝试过使用否定的前瞻^(?!\.).+?,但它似乎无法正常工作。
请注意,我想通过使用[a-zA-Z< plus all other possible chars minus the dot >] 排除. 来避免这样做

有什么建议吗?

【问题讨论】:

    标签: regex dotfiles


    【解决方案1】:

    应该这样做:

    ^[^.].*$
    

    [^abc] 将匹配任何 a、b 或 c

    【讨论】:

    • 这个答案不正确,因为. 必须转义为\.。请参阅下面的答案。
    • 我不认为点与括号表达式有特殊含义。 . .以上对我有用。
    • 确实如此。奇怪但没关系。
    • .不需要在字符类中转义。
    • 感谢您提醒我负面课程!正则表达式不花时间生锈;)我正在阅读神话中的 onigoruma 文档,但完全错过了它(geocities.jp/kosako3/oniguruma/doc/RE.txt)。也很高兴知道在课堂上不需要转义。
    【解决方案2】:

    转义.并否定可以以您拥有的名称开头的字符:

    ^[^\.].*$
    

    使用您的测试用例 here 成功测试。

    【讨论】:

      【解决方案3】:

      负前瞻^(?!\.).+$ 确实有效。这是Java:

          String[] files = {
              ".afile",
              ".anotherfile",
              "bfile.file",
              "bnotherfile.file",
              ".afolder/",
              ".anotherfolder/",
              "bfolder/",
              "bnotherfolder/",
              "", 
          };
          for (String file : files) {
              System.out.printf("%-18s %6b%6b%n", file,
                  file.matches("^(?!\\.).+$"),
                  !file.startsWith(".")
              );
          }
      

      输出是(as seen on ideone.com):

      .afile              false false
      .anotherfile        false false
      bfile.file           true  true
      bnotherfile.file     true  true
      .afolder/           false false
      .anotherfolder/     false false
      bfolder/             true  true
      bnotherfolder/       true  true
                          false  true
      

      还要注意非正则表达式 String.startsWith 的使用。可以说这是最好的、最易读的解决方案,因为无论如何都不需要正则表达式,startsWithO(1),而正则表达式(至少在 Java 中)是 O(N)

      注意空白字符串上的分歧。如果这是一个可能的输入,并且您希望它返回 false,您可以编写如下内容:

      !file.isEmpty() && !file.startsWith(".")
      

      另见

      【讨论】:

        【解决方案4】:

        嗯...否定字符类怎么样?

        [^.]
        

        排除点?

        【讨论】:

          猜你喜欢
          • 2022-01-13
          • 2023-01-11
          • 1970-01-01
          • 1970-01-01
          • 2011-02-22
          • 1970-01-01
          • 2015-09-18
          • 1970-01-01
          • 2021-09-07
          相关资源
          最近更新 更多