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 matchts.*".
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.txtwould still be matched by this pattern. If you need case-insensitive matching, you'd need to configure your file system'sPathMatcherwith 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
相关产品推荐
相关产品推荐

