3

What's the regular expression for positive whole numbers only? (zero is not allowed)

I was able to get the regular expression for numbers only which is ^\d+$. I've been trying to look for one online but it's already been an hour so I've decided to post it here on Stack Overflow.

matches:

1 || 2 || 444 || 9000 || 012

non-matches:

9.2 || -90
Toto
  • 86,179
  • 61
  • 85
  • 118
Randel Ramirez
  • 3,543
  • 19
  • 47
  • 61

7 Answers7

7

^0*[1-9]\d*$ will match all numbers excluding zero.

Prince John Wesley
  • 60,780
  • 12
  • 83
  • 92
  • 1
    @TimPietzcker, the `*?` is intended to be a "[lazy star](http://en.wikipedia.org/wiki/Regular_expression#Lazy_quantification)" , since `*` by itself is greedy. I don't think it's required (or makes any difference) for something as simple as `0*`, but it's valid notation nonetheless. – ghoti Mar 05 '12 at 15:37
  • It's valid but completely useless and slower because it leads to a lot of unnecessary backtracking. – Tim Pietzcker Mar 05 '12 at 16:00
6

May be you are looking for ^[1-9]+$ pattern. It'll match 1245, 2253 etc. But not 1003. or 0124. If you want to match the 3rd number (1003) as well use ^[1-9]\d*$ pattern.

In php you'd use

preg_match('/^[1-9]\d*$/', $subject, $matches)
Shiplu Mokaddim
  • 54,465
  • 14
  • 131
  • 183
3

This is obviously:

[1-9]\d*

(one to nine followed by zero or more digits.) This would exclude things like 0190, of course.

Ingo
  • 35,584
  • 5
  • 51
  • 97
2

I know you asked for a regex, but you might consider

$opts = array(
    'options' => array(
        'min_range' => 1,
        'max_range' => PHP_INT_MAX
    )
);
$n = filter_var($input, FILTER_VALIDATE_INT, $opts);
Daniel Lubarov
  • 7,674
  • 1
  • 36
  • 55
1
/^\+?([1-9]|0.)[0-9\.]*$/

this pattern may help you, but i think you must your programming language skills to do arithmetic check. for example in php . "$is_positive = $input > 0" yes it is so easy :)

  • thank you sir. yes, I just wanted to use regular expression to validate the user input for before I send the values to the database. Thank again sir. – Randel Ramirez Mar 05 '12 at 11:57
1

Try this

[1-9]\d*|[0]*[1-9]\d*
Naveen Kumar
  • 4,383
  • 1
  • 17
  • 36
0

Here's one that allows 0 up to 100 but not 01

^((([0]$)|[1-9][0-9]{0,1})|100)$

Agrapha
  • 13
  • 3