David Gard
David Gard

Reputation: 12047

Match any number (or negitive number) except '-0'

I have the followin RegEx to match any number between 1 and 4 digits in length, with a - character if so desired.

^[-]?\d{1,4}$

However, I'd like to exclude from the list of possible matches -0. I've tried the following, but it seems to break everything.

^[-]?(?!-0)\d{1,4}$

How can I achieve my goal?

Upvotes: 2

Views: 1963

Answers (3)

Denys Séguret
Denys Séguret

Reputation: 382102

Just put the excluding group before :

^(?!-0)-?\d{1,4}$

Note that you don't have to put the minus sign between brackets.

Upvotes: 1

Dmitry Poroh
Dmitry Poroh

Reputation: 3825

Just by concatenating positive and negative numbers:

^([0-9]{1,4})|(-[1-9][0-9]{0,3})$

Upvotes: 1

Maroun
Maroun

Reputation: 95948

Change to:

^(?!-?0)[-]?\d{1,4}$

This won't match any number that begins with "0" or with "-0".

If you want to match numbers beginning with "0" but not with "-0", use:

^(?!-0)[-]?\d{1,4}$

Upvotes: 1

Related Questions