for (int i = 0; i < pattern.length(); i++) {
char ch = pattern.charAt(i);
if (forceAbsolutePath && lastToken == LAST_TOKEN_START && ch != SLASH) {
throw new PatternSyntaxException("Syntax Error", pattern, i);
}
switch (ch) {
case SLASH:
// slash后面不能是slash, slash不能位于首字符(如果指定了force relative path的话)
if (lastToken == LAST_TOKEN_SLASH) {
throw new PatternSyntaxException("Syntax Error", pattern, i);
} else if (forceRelativePath && lastToken == LAST_TOKEN_START) {
throw new PatternSyntaxException("Syntax Error", pattern, i);
}
// 因为**已经包括了slash, 所以不需要额外地匹配slash
if (lastToken != LAST_TOKEN_DOUBLE_STAR) {
buf.append(REGEX_SLASH_NO_DUP);
}
lastToken = LAST_TOKEN_SLASH;
break;
case STAR:
int j = i + 1;
if (j < pattern.length() && pattern.charAt(j) == STAR) {
i = j;
// **前面只能是slash
if (lastToken != LAST_TOKEN_START && lastToken != LAST_TOKEN_SLASH) {
throw new PatternSyntaxException("Syntax Error", pattern, i);
}
lastToken = LAST_TOKEN_DOUBLE_STAR;
buf.append(REGEX_FILE_PATH);
} else {
// *前面不能是*或**
if (lastToken == LAST_TOKEN_STAR || lastToken == LAST_TOKEN_DOUBLE_STAR) {
throw new PatternSyntaxException("Syntax Error", pattern, i);
}
lastToken = LAST_TOKEN_STAR;
buf.append(REGEX_FILE_NAME);
}
break;
case QUESTION:
if (lastToken == LAST_TOKEN_START) {
buf.append(REGEX_WORD_BOUNDARY).append(REGEX_FILE_NAME_SINGLE_CHAR); // 前边界
} else if (i + 1 == pattern.length()) {
buf.append(REGEX_FILE_NAME_SINGLE_CHAR).append(REGEX_END_OF_PATH); // 后边界
} else {
buf.append(REGEX_FILE_NAME_SINGLE_CHAR);
}
lastToken = LAST_TOKEN_QUESTION;
break;
default:
// **后只能是slash
if (lastToken == LAST_TOKEN_DOUBLE_STAR) {
throw new PatternSyntaxException("Syntax Error", pattern, i);
}
if (Character.isLetterOrDigit(ch) || ch == UNDERSCORE || ch == DASH) {
// 加上word边界, 进行整字匹配
if (lastToken == LAST_TOKEN_START) {
buf.append(REGEX_WORD_BOUNDARY).append(ch); // 前边界
} else if (i + 1 == pattern.length()) {
buf.append(ch).append(REGEX_WORD_BOUNDARY); // 后边界
} else {
buf.append(ch);
}
} else if (ch == DOT) {
buf.append(ESCAPE_CHAR).append(DOT);
} else {
throw new PatternSyntaxException("Syntax Error", pattern, i);
}
lastToken = LAST_TOKEN_FILE_NAME;
}
}