Non Zero Number
-
Hi am looking for a RegEx that accepts a non-zero number only accepted examples : -10, -12.50, 5, 200, 103.05 etc not accepted : 0 Can you please help
It depends to a certain extent on what "non zero numbers" means, exactly. Does it mean
0
only and exactly, or does it have to not match 0. 0.0 0.00 etc. For the simple case of a just excluding a zero we can use the following perl regex:^[-+]?([1-9]\d+|[1-9]+\.|\d*\.\d+|0?\.\d+)$
I've anchored this on line start and end
^ ... $
, but you might have other requirements. This will match e.g 1.2 -15 0.03 .12 15. and -0.3, and does not accept any of.
,0
,0.
, or1.2.3
. However it does accept 0.0, 0.00, etc, and I have not yet found a way to eliminate them from the pattern. There might be a way using lookahead/lookbehind matches [Lookahead and Lookbehind Tutorial—Tips &Tricks](https://www.rexegg.com/regex-lookarounds.html), but so far I haven't been able to figure out how to tell the regex engine that the lookahead/behind should match the entire pattern. For example we can eliminate 0.0 by adding a negative lookbehind regex of(?, but this also elminates `0.0`3, which is not what is wanted. Maybe someone else knows how to resolve this. But maybe regex isn't the way to go. If you're working in Java or C# or C++ or ... , it's probably better to just read some input, check that the entire input parses as a number, convert to a number and then omit or complain if the value is zero - depending on what your use case is. Keep Calm and Carry On
-
It depends to a certain extent on what "non zero numbers" means, exactly. Does it mean
0
only and exactly, or does it have to not match 0. 0.0 0.00 etc. For the simple case of a just excluding a zero we can use the following perl regex:^[-+]?([1-9]\d+|[1-9]+\.|\d*\.\d+|0?\.\d+)$
I've anchored this on line start and end
^ ... $
, but you might have other requirements. This will match e.g 1.2 -15 0.03 .12 15. and -0.3, and does not accept any of.
,0
,0.
, or1.2.3
. However it does accept 0.0, 0.00, etc, and I have not yet found a way to eliminate them from the pattern. There might be a way using lookahead/lookbehind matches [Lookahead and Lookbehind Tutorial—Tips &Tricks](https://www.rexegg.com/regex-lookarounds.html), but so far I haven't been able to figure out how to tell the regex engine that the lookahead/behind should match the entire pattern. For example we can eliminate 0.0 by adding a negative lookbehind regex of(?, but this also elminates `0.0`3, which is not what is wanted. Maybe someone else knows how to resolve this. But maybe regex isn't the way to go. If you're working in Java or C# or C++ or ... , it's probably better to just read some input, check that the entire input parses as a number, convert to a number and then omit or complain if the value is zero - depending on what your use case is. Keep Calm and Carry On