I want to create a filter which checks if typed value is expected.
Allowed are negative and positive (without '+' sugn) numbers not preceding by zero. Also negative sign itself is allowed.
Problem is I can do search of negative number but I don't know how to add condition to find also minus.
I've tried to use lookaheads and whole this mechanism, but I've failed.
OK: -, -10, -54, 66, 0, 1
NOK: +, +1, -010, 010
Asked
Active
Viewed 807 times
-2

rainbow
- 1,161
- 3
- 14
- 29
-
1Show us the regex(es) you have tried. – CinCout Sep 28 '17 at 10:45
-
Also, why is just `-` OK? Doesn't make sense. – CinCout Sep 28 '17 at 10:51
-
@CinCout, because if I want to type negative number I need to start from "-" and I want to have "one stage" comparision. What is the point of showing non-working regexp? – rainbow Sep 28 '17 at 11:00
-
When you list your efforts, the community knows that you have tried something on your own and not just blatantly asking us to write something for you (which is off-topic on SO). That also helps the community to know your understanding of the topic/concept(s) and thus provide you an answer which will definitely be more helpful. – CinCout Sep 28 '17 at 11:08
3 Answers
2
What about that:
^(?:(?:-?(?:[1-9]\d*)?)|0)$
Explanation:
^ start marker
- literally matches - sign
? makes it optional
([1-9]\d*) start by non zero digit followed by optional digits
([1-9]\d*)? the question sign makes it optional
|0 means or a single zero
$ end marker

Mustofa Rizwan
- 10,215
- 2
- 28
- 43
-
1
-
1@Wli wow great catch ... definitely misseed due to hurry ! thanks – Mustofa Rizwan Sep 28 '17 at 11:02
-
1Yes, thats it. When I look at this, I think this regexp is far beyond my skills. – rainbow Sep 28 '17 at 11:06
0
Below is the correct working regex :
^-?(?:[1-9]\d*|0)?$
It will cover all the test cases

Bhawan
- 2,441
- 3
- 22
- 47