有时候使用replaceAll方法的时候会抛出PatternSyntaxException异常,通过看源代码发现。然后这个是没有显式的抛出异常,所以使用replaceAll方法的时候,没有try或者throw是完全没有错误的,因为PatternSyntaxException是一个运行时异常,就是只有运行时出错才抛出异常。不能算一个bug,只能是用这个方法的一个小陷阱。
public String replaceAll(String regex, String replacement) {
return Pattern.compile(regex).matcher(this).replaceAll(replacement);
}
/**
* Compiles the given regular expression into a pattern. </p>
*
* @param regex
* The expression to be compiled
*
* @throws PatternSyntaxException
* If the expression's syntax is invalid
*/
public static Pattern compile(String regex) {
return new Pattern(regex, 0);
}
string中的replace、replaceAll、split等方法实际是用到了正则表达式,然后正确中compile的静态方法会抛出该异常。
如果正则表达式中带有"(,[,-,/"等字符的时候则会抛出该异常,因为这些字符是正则表达式中的构造字符。