views:

108

answers:

2

Hi,

Excuse my ignorance. My knowledge of regular expressions is extremely limited.

I have the following regular expression on a regular expression validator.

^(\d{1,3},?(\d{3},?){0,2}\d{3}|\d{1,3})$

It currently allows zero. I need to update it so that it does not allow a value of 0.

[Edit: Just to clarify, I would like it to exclude a value of zero rather than a singular "0" - thanks]

Any help would be greatly appreciated.

Thanks zaps

+3  A: 

0 is allowed by the second part of your regex. Change it to:

^(\d{1,3},?(\d{3},?){0,2}\d{3}|[1-9]\d{0,2})$

It makes sure that the first digit is non zero, when the total number of digits are less than or equal to three.

The regex still allows patterns like 000,000,000 and 000,123 To fix that you can change the first part of the regex to:

^([1-9]\d{0,2},?(\d{3},?){0,2}\d{3}|[1-9]\d{0,2})$

Or rewrite it as

^[1-9]\d{0,2}(,?\d{3}){0,3}$

This still allows 123,456789 and 123456,789. Let us change it to:

^[1-9]\d{0,2}(?:(,\d{3}){0,3}|(\d{3}){0,3})$

This will allow 123,456,789 and 123456789 but not 123,456789 or 123456,789

Amarghosh
Doesn't this also eliminate, e.g., xy0 or x0y?
Timo
Wrong results. The intent is not to allow numbers with leading 0s. You're excluding too much.
reinierpost
The original question only asks how to disallow "0"s, it makes no mention of "leading" anything.
Chris S
No, it asks how to disallow 0, singular. Leading one to conclude that it is the value zero which needs to be excluded. You are correct, however, in that the OP could have included some additional info.
Timo
@Timo I think that's open to interpretation - OP hasn't clarified it.
Amarghosh
http://xkcd.com/386/ ;-)
Timo
@Timo So true, especially considering it's 8 PM here and I'm still in my office refreshing questions page in SO.
Amarghosh
@down-voters Updated the post.
Amarghosh
+6  A: 

You may be looking for something like this:

^[1-9]\d{0,2}(\d*|(,\d{3})*)$
reinierpost
Replace `\d{1,2}` with `\d{0,2}` and it’s perfect.
Gumbo
The original regex only allows values up to 999,999,999,999. This one will allow any number > 0. So `^[1-9]\d{1,2}(\d{0,9}|(,\d{3}){0,3})$` might be better. If that requirement is still there.
Tim Pietzcker
@Gumbo: done, thanks.@Tim: There are more differences. I was guessing those were unintentional.
reinierpost