示例代码
// Sanitize search string 对检测字符串做预处理
StringBuilder sb = new StringBuilder(search.length());
for (int i = 0; i < search.length(); ++i) {
char ch = search.charAt(i);
if (Character.isLetterOrDigit(ch) || ch == ' ' || ch == '\'') {
sb.append(ch);
}
}
search = sb.toString();
// Construct regex dynamically from user string 处理后再进行正则校验
String regex = "(.*? +public\\[\\d+\\] +.*" + search + ".*)";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(fileName);
return m.matches();