String str ='?';
matches(str),
因为传了?导致matches()发生了PatternSyntaxException。
有什么方法能在调用matches前对str进行整形、不让异常发生呢?
不只是是针对“?”、所有有可能发生异常的表达式都要整形。有什么写法吗?
也就是说哪种表达式会发生PatternSyntaxException?
在使用matches()方法时,传入的参数会被当做正则表达式来解析。如果传入的参数不符合正则表达式的语法规则,就会导致PatternSyntaxException异常的发生。
为了避免这种情况的发生,可以使用Pattern.quote()方法来对字符串进行整形,将其转化为普通字符串。例如,可以将传入的参数str进行如下处理:
String str = "?";
String regex = Pattern.quote(str);
if (str.matches(regex)) {
// 进行匹配操作
}
通过使用Pattern.quote()方法,可以将传入的参数str转化为普通字符串,避免了PatternSyntaxException的发生。
另外,需要注意的是,任何包含特殊字符的正则表达式都有可能导致PatternSyntaxException异常的发生。其中,特殊字符包括但不限于: \ ^ $ . | ? * + ( ) [ ] { } 。因此,在使用正则表达式时,需要对包含特殊字符的字符串进行转义处理,或者通过使用Pattern.quote()方法来对字符串进行整形,避免这种异常的发生。
这个建议你还是加上 try catch ,因为输入并不能100%控制
或者在Matches之前用 isMatch 先判断下
正则表达式、异常处理
下面给出一个对正则表达式进行检查和编译的工具类RegexUtils的示例代码:
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
public class RegexUtils {
/**
* 检查正则表达式是否包含非法字符
*
* @param regex 正则表达式
* @return 是否包含非法字符
*/
public static boolean checkRegex(String regex) {
try {
Pattern.compile(regex);
} catch (PatternSyntaxException e) {
return false;
}
return true;
}
/**
* 编译正则表达式
*
* @param regex 正则表达式
* @return Pattern对象,编译成功返回,编译失败返回null
*/
public static Pattern compileRegex(String regex) {
try {
return Pattern.compile(regex);
} catch (PatternSyntaxException e) {
System.err.println("Invalid regex: " + regex);
e.printStackTrace();
}
return null;
}
}
使用方法:
String regex = "\\d*";
if (RegexUtils.checkRegex(regex)) {
Pattern pattern = RegexUtils.compileRegex(regex);
if (pattern != null) {
Matcher matcher = pattern.matcher("123");
// do something
}
} else {
System.out.println("Invalid regex!");
}