3

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;
    }
1
  • 2
    use an online tester/debugger for regex to verify regex101.com Tim's answer is correct... Commented Apr 7, 2019 at 15:32

1 Answer 1

6

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}
Sign up to request clarification or add additional context in comments.

3 Comments

If the goal is to match any number between 0 and 9999, I think you want {1,4} as a quantifier?
@JornVernee I guess that would depend on whether zero would be fixed width (0000), or not (just 0). I am assuming fixed width.
correct also in the explanation [0-9]{4} to [0-9]{2}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.