Created
May 20, 2024 15:45
-
-
Save jfuerth/840e0814e247a245ae38e0ccc6b1991c to your computer and use it in GitHub Desktop.
Convert shell-like glob/wildcard to regex and match a string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private boolean matchesAnyGlob(String value, Collection<String> globs) { | |
// convert globs to regex | |
StringBuilder sb = new StringBuilder(); | |
sb.append("("); | |
for (String glob : globs) { | |
if (sb.length() > 1) { | |
sb.append("|"); | |
} | |
String[] parts = glob.splitWithDelimiters("[*?]", 0); | |
for (int i = 0; i < parts.length; i++) { | |
// add the literal part | |
if (parts[i].length() > 0) { | |
sb.append("\\Q").append(parts[i]).append("\\E"); | |
} | |
// add the wildcard part (unless at end of input) | |
if (++i < parts.length) { | |
sb.append(switch (parts[i]) { | |
case "*" -> ".*"; | |
case "?" -> "."; | |
default -> throw new AssertionError("Unexpected glob char " + parts[i]); | |
}); | |
} | |
} | |
} | |
sb.append(")"); | |
System.err.printf("Glob for %s is %s%n", globs, sb.toString()); | |
return value.matches(sb.toString()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment