4

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
  • 89,455
  • 62
  • 89
  • 125
Randel Ramirez
  • 3,671
  • 20
  • 49
  • 63

7 Answers7

8

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

Prince John Wesley
  • 62,492
  • 12
  • 87
  • 94
  • 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
  • 56,364
  • 17
  • 141
  • 187
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
  • 36,037
  • 5
  • 53
  • 100
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,796
  • 1
  • 37
  • 56
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,543
  • 1
  • 18
  • 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