我对正则表达式非常陌生,如何编写正则表达式来允许 null 或任何大于零的正数?
@Getter
@Setter
public class CacheCreateRequest {
.
.
.
@Pattern(regexp = RegexConstants.REGEX_POSITIVE_INTEGERS, message =
I18NKey.VALIDATION_FIELD_REPLICATION)
private Integer replication;
}
如何在“REGEX_POSITIVE_INTEGERS”中指定 REGEX
public static final String REGEX_POSITIVE_INTEGERS = ".....";
谢谢
最佳答案
这是一种似乎有效的模式:
^(?!0+(?:\.0+)?)\d*(?:\.\d+)?$
Demo
说明:
^ 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
在我看来,使用否定前瞻断言来排除任何形式的零似乎是满足您的要求的最简单方法。排除零后,模式的其余部分匹配正数(或根本没有数字)就相当简单了。
关于java - java中允许空值或正非零数的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59892121/