0

I am really fresh to Regular Expression, how can I write a regex to allow either null or any positive numbers greater than zero?

@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"

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

Thanks

Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397
Unni
  • 91
  • 4

1 Answers1

0

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.

Tim Biegeleisen
  • 387,723
  • 20
  • 200
  • 263