Class GlobMatcher

java.lang.Object
eu.svjatoslav.commons.string.GlobMatcher

public class GlobMatcher extends Object
Matches strings against glob-style wildcard patterns.

This class provides simple glob pattern matching similar to shell wildcards, using two special characters:

  • * - Matches any sequence of characters (zero or more)
  • ? - Matches exactly one character

All other characters match literally (case-sensitive).

Example patterns and matches:


 "*.txt" matches: "file.txt", "document.txt", ".txt"
 "*.txt" does NOT match: "file.TXT" (case-sensitive)

 "file?.txt" matches: "file1.txt", "fileA.txt", "file_.txt"
 "file?.txt" does NOT match: "file.txt", "file12.txt"

 "test*" matches: "test", "testing", "test123"
 "*test" matches: "test", "mytest", "123test"

 "*_*" matches: "a_b", "hello_world", "_"
 

This is simpler than regular expressions but useful for basic pattern matching in file name filtering, simple validation, or user-friendly pattern input.

Example usage:


 if (GlobMatcher.match("document.TXT", "*.txt")) {
     // This will NOT match (case-sensitive)
 }

 if (GlobMatcher.match("image.jpg", "*.jpg")) {
     // This will match
 }

 if (GlobMatcher.match("file123", "file?*")) {
     // This will match (? for one char, * for remaining)
 }
 

Null handling: Both string and pattern arguments are handled gracefully - if either is null, the result is false.

  • Method Details

    • match

      public static boolean match(String inputString, String wildcardExpression)
      Tests if an input string matches a wildcard expression.

      The wildcard expression uses:

      • * - matches any sequence of characters (zero or more)
      • ? - matches exactly one character

      All other characters must match exactly (case-sensitive).

      Matching rules:

      • Empty pattern matches empty string only
      • Pattern "*" matches any string (including empty)
      • Pattern "?" matches any single character
      • Null inputs result in false

      Example:

      
       GlobMatcher.match("file.txt", "*.txt");     // true
       GlobMatcher.match("file.TXT", "*.txt");     // false (case)
       GlobMatcher.match("file1", "file?");        // true
       GlobMatcher.match("file", "file?");         // false (too short)
       GlobMatcher.match("", "*");                 // true
       GlobMatcher.match("", "?");                 // false
       GlobMatcher.match(null, "*");               // false
       
      Parameters:
      inputString - the string to test against the pattern. May be null (returns false).
      wildcardExpression - the wildcard pattern to match against. May be null (returns false).
      Returns:
      true if the input string matches the wildcard pattern, false if it does not match or either argument is null.