user21
user21

Reputation: 1351

do you know how to modify the regex to allow one '-' char at the beginning of the string

i have the existing regex pattern: /^-?(?!0\d)\d+\.?\d*$/,

Currently the above regex do not allow - char at beginning of the string

Do you know how to modify the regex to also allow one '-' input besides the above existing validation My attempt:

/^(?!0\d)\d+\.?\d*$/

but it doesn't work well.

Upvotes: 0

Views: 61

Answers (2)

The fourth bird
The fourth bird

Reputation: 163632

To modify the regex and accept only a - as well, you could make 2 optional parts, and assert that the string is not empty.

^(?!-?0\d|$)-?(?:\d+\.?\d*)?$
  • ^ Start of string
  • (?!-?0\d|$) Assert not optional - 0 and digit or end of string
  • -? Match optional -
  • (?:\d+\.?\d*)? Optionally match 1+ digits, optional . and 0+ digits
  • $ End of string

Regex demo

Upvotes: 1

Tom
Tom

Reputation: 890

You first supplied regex: /^-?(?!0\d)\d+\.?\d*$/ does permit a leading - (minus sign)

Upvotes: 0

Related Questions