通过pattern来匹配字符串,Pattern类的compile方法,接收一个字符串作为匹配模板

修仙得道 / 2023-08-02 / 原文

public static String extractSubstring(String input, String pattern) {
Pattern regexPattern = Pattern.compile(pattern);
Matcher matcher = regexPattern.matcher(input);

if (matcher.find()) {
return matcher.group(1);
}

return null;
}

input和pattern举例。为了提取“/p/erkezonghe.html”中的
erkezonghe,用模板
"/p/(.*?).html"去匹配。提取的就是括号中间的一部分,锚点是括号左右的东西。