DD
DevDash

Regex for Non-negative Integer

Regex Pattern

^(0|[1-9]\d*)$

Zero or positive integer

Quick Answer

The regex pattern for non-negative integer is `^(0|[1-9]\d*)$`. Zero or positive integer. This works in JavaScript, Python, Ruby, PHP, Java, and most regex engines that support PCRE syntax.

Test Examples

InputResult
0✓ Matches
1✓ Matches
42✓ Matches
100✓ Matches
-1✗ No match
1.5✗ No match
01✗ No match
abc✗ No match

Code Examples

javascript

const regex = /^(0|[1-9]\d*)$/;
const isValid = regex.test(value);

python

import re
pattern = r'^(0|[1-9]\d*)$'
if re.match(pattern, value):
    print("valid")

ruby

pattern = /^(0|[1-9]\d*)$/
if value =~ pattern
  puts "valid"
end

php

if (preg_match('/^(0|[1-9]\d*)$/', $value)) {
    echo "valid";
}

java

String pattern = "^(0|[1-9]\\d*)$";
boolean isValid = value.matches(pattern);

Frequently Asked Questions

Related Regex Patterns

Want API access + no ads? Pro coming soon.