I've tried many examples to disallow a single digit 0
. The closest one working is [^0]
but that matches on 20
, 30
, etc. I only want to match on 0
.
Asked
Active
Viewed 336 times
-3
-
Please, provide *examples*. For instance, which of `"0"`, `"0.0"`, `"-0"`, `"+0"`, `"00"`, `"zero: 0"`, `"0-0-0"`, `" 0 "` (spaces) should be matched? – Dmitry Bychenko May 25 '18 at 08:55
-
Possible duplicate of [Regex - Match whole string](https://stackoverflow.com/questions/6298566/regex-match-whole-string) – revo May 25 '18 at 08:59
2 Answers
2
Use start and end anchors to match the entire input being a zero:
^0$
Or to match a solitary zero within a string, use word boundaries:
\b0\b
Do disallow a solitary zero in the input use the above in a negative look ahead.
^(?!.*\b0\b).*

Bohemian
- 412,405
- 93
- 575
- 722
-
Thanks Bohemian. I'm trying to use 'regExp' with data-dojo-props to not allow '0' in the field although both positive and negative numbers are allowed. When using ^0$, it 'matches' on any number (5,6,7,etc). data-dojo-props="constraints:{min:-90,max:90,places:0}, required:true, invalidMessage:'Latitude degree is -90 to 90', regExp:'^0$', invalidMessage:'Latitude degree cannot be 0'" /> deg – JWK May 25 '18 at 09:00
-
@JWK I think your code sample should be in the original question, so please *[edit it!](https://stackoverflow.com/posts/50525218/edit)* It helps to show a lot better what you are trying to achieve. – Peter B May 25 '18 at 09:14
1
If you want to match not a zero but do want to allow positive and negative numbers you might use. This uses anchors ^
and $
to assert the start and the end of the string.
Without using anchors you could use a word boundary \b
:
That would match an optional plus or minus sign [+-]?
, a digit from 1 - 9 [1-9]
so it does not match a zero followed by zero or more times a digit [0-9]*

The fourth bird
- 154,723
- 16
- 55
- 70
-
This could be nitpicking :-) but it allows `0.0`. That wasn't in the question but would seem to be in the spirit of it to also disallow that. – Peter B May 25 '18 at 09:16
-
-
@PeterB Are you sure this matches `0.0`? [test 1](https://regex101.com/r/gESVfn/2) and [test 2](https://regex101.com/r/iA9DF9/2) – The fourth bird May 25 '18 at 09:20