Skip to content

Instantly share code, notes, and snippets.

@mingliangguo
Created April 2, 2022 23:08
Show Gist options
  • Save mingliangguo/d6dc170e9bb1ea740e4ed4203e6c6e45 to your computer and use it in GitHub Desktop.
Save mingliangguo/d6dc170e9bb1ea740e4ed4203e6c6e45 to your computer and use it in GitHub Desktop.
wildcardToRegexp
/**
* Expands glob expressions to regular expressions.
*
* @param globExp the glob expression to expand
* @return a string with the regular expression this glob expands to
*/
public static String wildcardToRegexp(String globExp) {
StringBuilder dst = new StringBuilder();
char[] src = globExp.replace("**/*", "**").toCharArray();
int i = 0;
while (i < src.length) {
char c = src[i++];
switch (c) {
case '*':
// One char lookahead for **
if (i < src.length && src[i] == '*') {
dst.append(".*");
++i;
} else {
dst.append("[^/]*");
}
break;
case '?':
dst.append("[^/]");
break;
case '.':
case '+':
case '{':
case '}':
case '(':
case ')':
case '|':
case '^':
case '$':
// These need to be escaped in regular expressions
dst.append('\\').append(c);
break;
case '\\':
i = doubleSlashes(dst, src, i);
break;
default:
dst.append(c);
break;
}
}
return dst.toString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment