简体   繁体   中英

Does String.matches(<pattern>) throw anything?

I am using this method to determine whether the input string from a TextField in javafx has this pattern AB123CD with the pattern ("\\D{2}\\d{3}\\D{2}") I am using a try catch enclosure, which catches a (hand)thrown PatternSyntaxException. I am asking this, because the PatternSyntaxException uses a String String Integer constructor, showing the exception like: error at index int ^ or something like that My problem is that I can't figure out how to get the right index to put in the constructor, or whether I can use any other Exception in replacement

This is the part of the code:

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 is a RuntimeException which is thrown when there's any syntax error in regex. There's no compile time exception thrown by String::matches method as it internally calls Pattern class's static method matches . Here's the source code:

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

Thus here you are catching PatternSyntaxException because you are explicitly throwing PatternSyntaxException here:

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

String.matches throws PatternSyntaxException when the regular expression's syntax is invalid . It's not used to tell whether the input matches the regex pattern.

Since \\\\D{2}\\\\d{3}\\\\D{2} is a valid regex, this catch (PatternSyntaxException e) will never be executed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM