Regex contain only numbers and does not contain only 0

Viewed 580

I would like to implement a regular expression that return true if:

  • The string contain only number
  • The string does not contain only 0 ( like 0000)

For example:

  • 1230456 => true
  • 888822200000 => true
  • 00000000 => false
  • fff => false

I started to implement this

private static final String ARTICLE_VALID_FORMAT = "\\d";
private static final Pattern ARTICLE_VALID_FORMAT_PATTERN = Pattern.compile(ARTICLE_VALID_FORMAT);

private boolean isArticleHasValidFormat(String article) {
    return StringUtils.isNotBlank(article) && ARTICLE_VALID_FORMAT_PATTERN.matcher(article).matches();
}

Now, it returns true if the article has only number. but i would like to test also if it is not all 0.

How to do that?

Thanks

4 Answers

You can use:

private static final String ARTICLE_VALID_FORMAT = "[0-9]*?[1-9][0-9]*";

which means:

  • Match zero or more digits; the ? means to match as few as possible before moving onto the next part
  • then one digit that's not a zero
  • then zero or more digits

Or, as Joachim Sauer suggested in comments:

private static final String ARTICLE_VALID_FORMAT = "0*[1-9][0-9]*";

which means:

  • Match zero or more zeros
  • then one digit that's not a zero
  • then zero or more digits

If you wanted to do it without regex, you could use (among many other ways):

    string.chars().allMatch(c -> c >= '0' && c <= '9')
 && string.chars().anyMatch(c -> c != '0')

The regex pattern \d*[1-9]\d* as given by @AndyTurner is a good way to do this. Another approach would be to try to parse the string input to a long, and then check that it is greater than zero:

private boolean isArticleHasValidFormat(String article) {
    try {
        if (Long.parseLong(article) > 0) return true;
    }
    catch (NumberFormatException e) {
    }

    return false;
}

This solution assumes that you are only concerned with finding positive numbers. If not, and you want to cater to negatives, then check num != 0 instead.

Try this condition.

(Integer.pasrseInt("0" + article.replaceAll("^[0-9]", "0")) != 0) ? true : false

the ["0" +] is to avoid NumberFormatException for empty string

You don't need to make a Pattern object. Just call matches function from the String class

article.matches("\\d*[1-9]\\d*");

It's the same regex as Andy Turner suggested.

Related