You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java NIO中Glob模式取反语法:如何匹配所有非ts.*的内容

Java Glob Pattern to Match Everything Except "ts.*"

Got it! Let's break this down clearly. In Java, when you need to use Glob patterns to match all content that doesn't fit the ts.* pattern, you'll leverage the negation syntax supported by Java's PathMatcher API.

The Exact Glob Pattern

The correct Glob syntax for this requirement is:

glob:!ts.*
  • The glob: prefix tells Java you're working with Glob (not regex) syntax.
  • The ! at the start negates the following pattern, meaning "match anything that does not match ts.*".

Code Example

Here's a quick, runnable example to see this in action:

import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.Paths;

public class NonTsGlobMatcher {
    public static void main(String[] args) {
        // Initialize the matcher with our negated Glob pattern
        PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:!ts.*");

        // Test various file paths
        Path tsFile = Paths.get("ts.txt");
        Path regularFile = Paths.get("report.pdf");
        Path otherTsFile = Paths.get("ts.config");
        Path unrelatedFile = Paths.get("data.ts");

        // Check matches
        System.out.println(matcher.matches(tsFile)); // false (matches ts.*, so negated)
        System.out.println(matcher.matches(regularFile)); // true (doesn't match ts.*)
        System.out.println(matcher.matches(otherTsFile)); // false (matches ts.*)
        System.out.println(matcher.matches(unrelatedFile)); // true (doesn't match ts.*)
    }
}

For Subdirectories

If you need to match files across all subdirectories while excluding ts.* files everywhere, use this pattern instead:

glob:**/!ts.*

The ** wildcard matches any number of parent directories, so this will exclude ts.* files no matter where they're located in the directory tree.

Key Notes

  • Glob patterns in Java are case-sensitive by default. So a file named TS.txt would still be matched by this pattern. If you need case-insensitive matching, you'd need to configure your file system's PathMatcher with case-insensitive options.
  • The negation applies to the entire pattern: any path that would be matched by ts.* is rejected, and all others are accepted.

内容的提问来源于stack exchange,提问作者Steve

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:20:22