[英]Does String.matches(<pattern>) throw anything?
我正在使用此方法确定javafx中TextField的输入字符串是否具有模式AB123CD和模式(“ \\ D {2} \\ d {3} \\ D {2}”),我正在使用try catch附件,捕获(手动)抛出的PatternSyntaxException。 我问这个问题,因为PatternSyntaxException使用String String Integer构造函数,显示异常,如:index int ^或类似的错误我的问题是我无法弄清楚如何获取正确的索引以放入构造函数,或者我是否可以使用其他任何异常替换
这是代码的一部分:
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)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.