0

我正在使用此方法来确定来自 javafx 中 TextField 的输入字符串是否具有此模式 AB123CD 与模式 ("\D{2}\d{3}\D{2}") 我正在使用 try catch 附件,它捕获(手动)抛出的 PatternSyntaxException。我问这个,因为 PatternSyntaxException 使用 String String Integer 构造函数,显示异常,例如:索引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());
    }
4

2 回答 2

0

PatternSyntaxExceptionRuntimeException当正则表达式中存在任何语法错误时抛出的。方法没有抛出编译时异常, 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);
于 2018-07-07T15:43:33.970 回答
0

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

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

于 2018-07-07T15:44:29.427 回答