KWeiss
KWeiss

Reputation: 3144

Regex to match positive or negative number or empty string, but not '-' alone

I want to validate numbers in an input in Javascript.

The input should accept:

I have used this regex:

^(-?)[\d]*$

It works well, but it also accepts only the minus character alone '-' . I want to exclude this possibility. I could of course replace * with +, but that would exclude the empty string.

How can I do it so that a - must be followed by at least one number, but a completely empty string is still OK?

Upvotes: 7

Views: 8737

Answers (2)

Mrithyunjay Jagannath
Mrithyunjay Jagannath

Reputation: 39

The below regex should fulfill your requirements:

^(|-?\d+)$

Here is a demo

Let's dissect the regex to understand how it works

  • The outer body ^()$: ^ denotes the start of the string and $ signifies the end. () tells the matcher to capture everything enclosed. So in our case, it means that our input should be an exact match.
  • | is a boolean OR i.e. returns positive if either of the regexes is satisfied.
  • -?\d+ matches the positive and negative numbers as follows
    1. -? matches - between zero and one times
    2. \d+ matches a digit between one to unlimited times
  • There is another check which essentially isn't there. If you look closely the expression does not have anything before the | OR operator. That is the null or the empty input check.
  • These combined with the OR means that the input can either be nothing or an integer.

With all these combined, we arrive at the required regex.

Upvotes: 3

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

You may make the digits obligatory and enclose the whole number matching part with an optional group:

/^(?:-?\d+)?$/

See the regex demo

Details

  • ^ - start of the string
  • (?:-?\d+)? - an optional non-capturing group matching 1 or 0 occurrences of:
    • -? - an optional -
    • \d+ - 1 or more digits
  • $ - end of string.

Upvotes: 7

Related Questions