简体   繁体   English

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

[英]Regular expression to allow null or positive non-zero numbers in java

I am really fresh to Regular Expression, how can I write a regex to allow either null or any positive numbers greater than zero?我对正则表达式真的很陌生,如何编写正则表达式以允许 null 或任何大于零的正数?

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

How can I specify the REGEX in "REGEX_POSITIVE_INTEGERS"如何在“REGEX_POSITIVE_INTEGERS”中指定 REGEX

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

Thanks谢谢

Here is a pattern which seems to be working:这是一个似乎有效的模式:

^(?!0+(?:\.0+)?)\d*(?:\.\d+)?$

Demo演示

Explanation:解释:

^                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

Using a negative lookahead assertion to rule out any form of zero seemed to me to be the easiest way to meet your requirement.使用否定前瞻断言来排除任何形式的零在我看来是满足您的要求的最简单方法。 With zero out of the way, the rest of the pattern to match a positive number (or no number at all) is fairly straightforward.排除零,匹配正数(或根本没有数字)的模式的其余部分相当简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM