Skip to content

Commit 31b1ad6

Browse files
committed
fix:抛出PatternSyntaxException
1 parent 712f2b7 commit 31b1ad6

File tree

2 files changed

+18
-15
lines changed

2 files changed

+18
-15
lines changed

core/src/main/java/com/taobao/arthas/core/util/RegexCacheManager.java

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22

33
import com.taobao.arthas.core.shell.term.impl.http.session.LRUCache;
44
import java.util.regex.Pattern;
5-
import java.util.regex.PatternSyntaxException;
65

76
/**
87
* 正则表达式缓存管理器
@@ -44,14 +43,11 @@ public Pattern getPattern(String regex) {
4443
synchronized (regexCache) {
4544
pattern = regexCache.get(regex);
4645
if (pattern == null) {
47-
try {
48-
// 缓存未命中,编译正则表达式
49-
pattern = Pattern.compile(regex);
50-
regexCache.put(regex, pattern);
51-
} catch (PatternSyntaxException e) {
52-
// 捕获正则表达式语法错误,返回null,保持与原来相同的错误处理行为
53-
return null;
54-
}
46+
// 缓存未命中,编译正则表达式
47+
// 不捕获PatternSyntaxException,让异常向上抛出,以便及时发现无效的正则表达式
48+
pattern = Pattern.compile(regex);
49+
// 缓存编译结果
50+
regexCache.put(regex, pattern);
5551
}
5652
}
5753

core/src/main/java/com/taobao/arthas/core/util/matcher/RegexMatcher.java

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,17 +9,24 @@
99
*/
1010
public class RegexMatcher implements Matcher<String> {
1111

12-
private final Pattern pattern;
12+
private final String pattern;
13+
private Pattern compiledPattern;
1314

1415
public RegexMatcher(String pattern) {
15-
// 使用正则表达式缓存
16-
this.pattern = RegexCacheManager.getInstance().getPattern(pattern);
16+
this.pattern = pattern;
1717
}
1818

1919
@Override
2020
public boolean matching(String target) {
21-
return null != target
22-
&& null != pattern
23-
&& pattern.matcher(target).matches();
21+
if (null == target || null == pattern) {
22+
return false;
23+
}
24+
25+
// 在第一次matching时才编译正则表达式
26+
if (compiledPattern == null) {
27+
compiledPattern = RegexCacheManager.getInstance().getPattern(pattern);
28+
}
29+
30+
return compiledPattern != null && compiledPattern.matcher(target).matches();
2431
}
2532
}

0 commit comments

Comments
 (0)