-2

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

rainbow
  • 1,161
  • 3
  • 14
  • 29
  • 1
    Show 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 Answers3

2

What about that:

^(?:(?:-?(?:[1-9]\d*)?)|0)$

Regex 101 Demo

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
0

Below is the correct working regex :

^-?(?:[1-9]\d*|0)?$

It will cover all the test cases

Bhawan
  • 2,441
  • 3
  • 22
  • 47
0

Use this: ^-?(?:(?:[1-9]\d*|0))?$

Demo

Start with an optional -, then make sure the first digit is anything but 0 with the rest being as many digits as possible. Also handle the special case of 0 only.

CinCout
  • 9,486
  • 12
  • 49
  • 67