Leandro Garcia
Leandro Garcia

Reputation: 3228

regex negate numbers

Currently I have this regular expression to validate letters, dash and spaces.

/^[a-zA-Z-\s]*$/

Now, I am quite confused how can this be rewritten to have a rule that it will accept everything except numbers?

Upvotes: 2

Views: 495

Answers (3)

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123397

just use \D that has the same meaning of [^\d]

/\D/

Upvotes: 0

stema
stema

Reputation: 92986

To have anything except something, you need a negated character class

 [^\d]

A character class that starts with ^ is a negated class, \d is a predefined class that contains digits.

If you have really only digits you can shorten this further, there is also a predefined negation of \d that is \D

So [^\d] = \D

You may find this link to a regex reference on regular-expressions.info useful

Upvotes: 3

drf
drf

Reputation: 8699

/^\D*$/

\D matches any character that is not a digit. The above expression matches any string that is comprised entirely of non-digits.

(This pattern matches "abc", does not match "123" or "ab2c".)

Upvotes: 1

Related Questions