Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • empty input ''
  • positive number '123'
  • negative number '-123'

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?

like image 621
KWeiss Avatar asked Jan 04 '18 11:01

KWeiss


People also ask

Does empty regex match everything?

An empty regular expression matches everything.

How do you check if a regex matches a string?

If you need to know if a string matches a regular expression RegExp , use RegExp.prototype.test() .

How do you match expressions in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).

Is used for zero or more occurrences in regex?

A regular expression followed by an asterisk ( * ) matches zero or more occurrences of the regular expression. If there is any choice, the first matching string in a line is used.


1 Answers

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.
like image 115
Wiktor Stribiżew Avatar answered Nov 03 '22 01:11

Wiktor Stribiżew