// 代碼 1
String regex = "com/xxx/ * /test";
String string = "com/xxx/utils/test";
System.out.println(string.matches(regex)); // false
// 代碼 2
String regex = "com/xxx/ * /pattern/ * ";
String string = "com/xxx/test/pattern/PatternTest1";
System.out.println(string.matches(regex)); // false
* 不是通配符,是量詞「前面字符 0 次或多次」 *(空格後跟 *)匹配「0 個或多個空格」,而非「任意字符」。/ * / 僅匹配 / /、/ / 等帶空格的路徑,不匹配 /utils/。| 需求 | 正則片段 | 說明 |
|---|---|---|
| 匹配任意非斜槖字符(路徑段) | [^/]+ | [^/] 非斜槖字符,+ 至少一個 |
| 匹配任意字符(含斜槖) | .* | . 任意字符(除換行),* 任意次 |
| 匹配字母數字下劃線 | \w+ | 等價 [a-zA-Z0-9_]+ |
// 需求 1:com/xxx/任意路徑段/test
String regex1 = "com/xxx/[^/]+/test";
// 或更嚴格:com/xxx/\w+/test
// 需求 2:com/xxx/任意路徑/pattern/任意路徑
String regex2 = "com/xxx/[^/]+/pattern/[^/]+";
// 或:com/xxx/.*/pattern/.* (貪婪匹配,注意性能)
用戶輸入 com.xxx.*.pattern.*(以點分隔,* 為通配符),需轉換為 Java 正則:
public static String globToRegex(String glob) {
StringBuilder sb = new StringBuilder();
for (char c : glob.toCharArray()) {
switch (c) {
case '*': sb.append("[^.]*"); break; // 匹配非點字符任意次(路徑段)
case '.': sb.append("\\."); break; // 轉義點
case '?': sb.append("[^.]"); break; // 單字符通配
default: sb.append(c);
}
}
return sb.toString();
}
// 測試
String userInput = "com.xxx.*.pattern.*";
String regex = globToRegex(userInput);
// 結果:com\.xxx\.[^.]*\.pattern\.[^.]*
// 匹配:com.xxx.test.pattern.PatternTest1.class ✓
String.matches(regex) 是整字符串匹配,等同於 ^regex$。* 單獨使用無意義,必須跟在字符/字符集後(如 .*、\w*、[^/]*)。[^/]+ 精確匹配單段,避免 .* 貪婪跨段匹配導致錯誤或性能問題。. * ? 等)再映射為正則語法。