How Do I Add Regex To @Pattern Annotation To Match One Of Two Specific Strings Or A Null?

- 1 answer

I've added @Pattern annotation to a query parameter in my rest controller (SpringBoot Kotlin). I would like the regex in the pattern to accept -

optionA or optionB or null (nothing/an empty string)

The following works, but of course does not include the empty option -

    @Pattern(regexp = "(?i)optionA||(?i)optionB")

This does not work -

    @Pattern(regexp = "(?i)optionA||(?i)optionB||^\\s*\$")

Can anybody help me with this? :) Thanks!



Inside the @Pattern annotation, the pattern is used to match the entire string, so you can use

@Pattern(regexp = "(?i)(?:optionA)?")

which is actually \A(?i)(?:optionA)?\z:

  • \A - start of string (implicit here)
  • (?i) - case insensitive embedded flag option
  • (?:optionA)? - an optional non-capturing group that matches optionA or empty string
  • \z - end of string (implicit here).

The null is a memory address, not a string, it cannot be matched with regex, as regex only deals with strings.