regex—java中允许空或正非零数的正则表达式

ruarlubt  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(234)

我对正则表达式非常熟悉,如何编写正则表达式来允许null或任何大于零的正数?

@Getter
@Setter
public class CacheCreateRequest {
.
.
.
    @Pattern(regexp = RegexConstants.REGEX_POSITIVE_INTEGERS, message = 
    I18NKey.VALIDATION_FIELD_REPLICATION)
    private Integer replication;
}

如何在“regex\u正整数”中指定regex

public static final String REGEX_POSITIVE_INTEGERS = ".....";

谢谢

insrf1ej

insrf1ej1#

以下是一个似乎有效的模式:

^(?!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

在我看来,使用否定的前瞻性Assert来排除任何形式的零似乎是满足您的要求的最简单的方法。如果不使用零,那么匹配正数(或者根本没有数字)的模式的其余部分就相当简单了。

相关问题