如何将正则表达式添加到 @Pattern 注释以匹配两个特定字符串之一或空值?

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

我已将 @Pattern 注释添加到我的其余控制器 (SpringBoot Kotlin) 中的查询参数。我希望模式中的正则表达式接受 -

选项A或选项B或空值(nothing/an空字符串)

以下有效,但当然不包括空选项 -

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

这行不通 -

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

有人可以帮我解决这个问题吗? :) 谢谢!

我在 https://regex101.com/ 上尝试了这个 optionA|optionB|^\s$ 并且效果很好。你能试试你的应用程序来检查吗?

@Pattern注解里面,模式是用来匹配整个字符串的,所以可以用

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

实际上是 \A(?i)(?:optionA)?\z:

  • \A - 字符串的开头(此处隐含)
  • (?i) - 不区分大小写的嵌入标志选项
  • (?:optionA)? - 匹配 optionA 或空字符串
  • 的可选 non-capturing 组
  • \z - 字符串结尾(此处隐含)。

null是内存地址,不是字符串,不能用regex匹配,因为regex只处理字符串。