...

View Full Version : Regular expression for natural numbers



rickyd
09-11-2008, 09:56 PM
I'm trying to write an expression to validate a natural number. It should accept any non-negative integer including '0' but not '01'. It seems like the simplest regular expression imaginable, but I can't get it to work correctly in javascript. The problem is that it will except negative numbers, and will in fact accept 'x10'.


function isNaturalNumber (str) {
var pattern = /^(0)|([1-9][0-9]*)$/;
return pattern.test(str);
}

It seems to honor the '$' but not the '^'. I know there are other ways to accomplish this, but I'd really like to understand why this doesn't work, since I need to validate some more complicated data.

mrhoo
09-12-2008, 12:52 AM
Parentheses.
also, [0-9] = \d

var pattern = /^(0|([1-9]\d*))$/;


function isNaturalNumber (str) {
var pattern = /^(0|([1-9]\d*))$/;
return pattern.test(str);
}

liorean
09-12-2008, 03:10 AM
As long as you're actually not using the submatches
var pattern = /^(?:0|[1-9]\d*)$/;

rickyd
09-12-2008, 08:39 AM
Thanks both for your help. I understand that \d == [0-9], but I find the latter much easier to read. I can see why both suggestions are improvements, but I still don't understand why my original code didn't work. Can you explain?

Philip M
09-12-2008, 10:16 AM
var pattern = /^(0)|([1-9][0-9]*)$/;

specifies that the regex will return true if either:

a) The first character is the digit 0 regardless of what follows (so 01 or 0x will return true)

OR

b) the pattern includes (but not necessarily starts with) a digit from 1-9 followed by zero or more digits from 0-9 at the end of the string.
(so x22 will return true but 22x will return false)

As mrhoo says, it is a matter of parentheses.


You can test your regular expressions at: http://www.claughton.clara.net/regextester.html

rickyd
09-12-2008, 11:00 AM
Got it. Thanks so much.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum