Home > database >  How do I add regex to @Pattern annotation to match one of two specific strings or a null?
How do I add regex to @Pattern annotation to match one of two specific strings or a null?

Time:02-20

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!

CodePudding user response:

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.

CodePudding user response:

I tryed this optionA|optionB|^\s$ on https://regex101.com/ and worked well. Could you try on your app to check?

  • Related