String.matches(<pattern>) 会抛出什么吗?



我正在使用此方法来确定javafx中TextField的输入字符串是否具有此模式AB123CD模式("\D{2}\d{3}\D{2}"( 我正在使用一个 try catch 外壳,它捕获一个(手动(抛出的 PatternSyntaxException。 我问这个,因为 PatternSyntaxException 使用字符串字符串整数构造函数,显示异常如下: 索引int^ 处出错 或类似的东西 我的问题是我不知道如何获得正确的索引来放入构造函数,或者我是否可以使用任何其他 Exception 来替换

这是代码的一部分:

try {
if(!tfTarga.getText().matches("\D{2}\d{3}\D{2}"))
throw new PatternSyntaxException(tfTarga.getText(), tfTarga.getText(), 0);
else {
this.olCCar.add(new CCar(new ContractCars(new Contract(this.comboCont.getValue()), this.tfTarga.getText(), LocalDate.now(), Integer.parseInt(this.tfPrezzo.getText()))));
this.tfTarga.setText("");
this.tfPrezzo.setText("");
}
} catch (PatternSyntaxException e) {
alert("Error", "Format Error", e.getLocalizedMessage());
}

PatternSyntaxException 是一个RuntimeException,当正则表达式中存在任何语法错误时会抛出它。String::matches方法没有引发编译时异常,因为它在内部调用Pattern类的静态方法matches。以下是源代码:

public static boolean matches(String regex, CharSequence input) {
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
return m.matches();
}

因此,在这里你抓住了PatternSyntaxException因为你在这里明确地抛出PatternSyntaxException

if(!tfTarga.getText().matches("\D{2}\d{3}\D{2}"))
throw new PatternSyntaxException(tfTarga.getText(), tfTarga.getText(), 0);
String.matches

正则表达式的语法无效时抛出PatternSyntaxException。它不用于判断输入是否与正则表达式模式匹配。

由于\D{2}\d{3}\D{2}是有效的正则表达式,因此此catch (PatternSyntaxException e)永远不会执行。

最新更新