我对正则表达式真的很陌生,如何编写正则表达式以允许 null 或任何大于零的正数?
@Getter
@Setter
public class CacheCreateRequest {
.
.
.
@Pattern(regexp = RegexConstants.REGEX_POSITIVE_INTEGERS, message =
I18NKey.VALIDATION_FIELD_REPLICATION)
private Integer replication;
}
如何在"REGEX_POSITIVE_INTEGERS"中指定正则表达式
public static final String REGEX_POSITIVE_INTEGERS = ".....";
谢谢
这是一个似乎有效的模式:
^(?!0+(?:.0+)?)d*(?:.d+)?$
演示
解释:
^ from the start of the input
(?!0+(?:.0+)?) assert that zero with/without a decimal zero component does not occur
d* then match zero or more digits (includes null/empty case)
(?:.d+)? followed by an optional decimal component
$ end of the input
在我看来,使用消极的前瞻断言来排除任何形式的零似乎是满足您需求的最简单方法。 在零消失的情况下,匹配正数(或根本没有数字(的其余模式相当简单。