J.Eve
J.Eve

Reputation: 67

Java exception pattern

I'm trying to write a code for exception. If the input does not match with the pattern below (this is just example) it will throw an exception message.

8454T3477-90

This is the code that I came up with. However, I'm not sure if this is the right patter...

public void setLegalDescription(String legalDescription) throws MyInvalidLegalDescriptionException
    {
        String valid = ("[0-9999][A-Z][0-9999]-[0-99]");
        if (!legalDescription.matches(valid))
        {
            //throw new MyInvalidLegalDescriptionException("Invalid format! Should be " + "e.g 4050F8335-14");
        }
        this.legalDescription = legalDescription;
    }

Upvotes: 3

Views: 109

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522797

Your pattern is slightly off. Try this version:

String valid = ("[0-9]{4}[A-Z][0-9]{4}-[0-9]{2}");
if (!legalDescription.matches(valid))
{
    // throw new MyInvalidLegalDescriptionException("Invalid format! Should be " + "e.g 4050F8335-14");
}

An explanation of the regex:

[0-9]{4}   any 4 digits
[A-Z]      any capital letter
[0-9]{4}   any 4 digits
-          a dash
[0-9]{2}   any 2 digits

It should be noted that [0-9999] does not match any number between 0 and 9999. Rather, it actually just matches a single digit between 0 and 9.

If the width of your identifier is not fixed, then perhaps use this pattern:

[0-9]{1,4}[A-Z][0-9]{1,4}-[0-9]{1,2}

Upvotes: 6

Related Questions