Created
April 2, 2022 23:08
-
-
Save mingliangguo/d6dc170e9bb1ea740e4ed4203e6c6e45 to your computer and use it in GitHub Desktop.
wildcardToRegexp
This file contains hidden or 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
/** | |
* 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