4

I am trying to develop a simple REGEX in Java with pattern like that :

@Pattern(regexp = "[a-zA-Z]{2}[0-9]{1}[2-8]{1}" , message = "The format is invalid")

but this message is still displayed when the field is empty, so i want to show this message only when the field is not empty (i want that the field is will be not required).

Thank you.

6
  • 2
    Please post valid Java code. What you posted won't compile. Commented Sep 23, 2019 at 10:34
  • Do you mean either empty or that pattern by making it optional? ^(?:[a-zA-Z]{2}[0-9][2-8])?$ regex101.com/r/pKrWA1/1 Commented Sep 23, 2019 at 10:34
  • Hi. There's a syntax error in the snippet you've included. Also, you seem to be using some sort of a magic framework. Do at least mention its name somewhere (or a full path, with the package name, of the @Pattern annotation). There's just far too much missing from this question. Commented Sep 23, 2019 at 10:34
  • 1
    (OT: {1} is superfluous.) Commented Sep 23, 2019 at 10:44
  • Just curious, what are you trying to match with [0-9]{1}[2-8]{1}? Commented Sep 23, 2019 at 11:54

2 Answers 2

3

Try using the following regex, which matches both your expected string and empty string:

[a-zA-Z]{2}[0-9]{1}[2-8]{1}|^$

Java code:

@Pattern(regexp = "[a-zA-Z]{2}[0-9]{1}[2-8]{1}|^$", message = "The format is invalid")
Sign up to request clarification or add additional context in comments.

Comments

2

You could make your whole pattern optional using a non capturing group (?:...)?to match either an empty string or the whole pattern.

Note that you can omit the {1} part.

^(?:[a-zA-Z]{2}[0-9][2-8])?$

Regex demo

@Pattern(regexp = "^(?:[a-zA-Z]{2}[0-9][2-8])?$" , message = "The format is invalid")

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.