0

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());
    }
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
  • 1
    Please show us the entire relevant code, or at least enough of it to get your point across. Your regex looks fine, but that doesn't mean your code is OK. – Tim Biegeleisen Jul 07 '18 at 15:37
  • 1
    PatternSyntaxException is supposed to signal an error in the syntax of a pattern (as its name implies). I(s not supposed to signal that a string doesn't match a regexp. Just show your alert inside the if block. No need for an exception. – JB Nizet Jul 07 '18 at 15:44

2 Answers2

0

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);
Shubhendu Pramanik
  • 2,711
  • 2
  • 13
  • 23
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.

xingbin
  • 27,410
  • 9
  • 53
  • 103