14

I need a regular expression pattern that matches any number including 1-9 numbers except 2?

My attempt:

([1-9][^2])

But this doesn't work for me.

dda
  • 6,030
  • 2
  • 25
  • 34
Mohammad Masoudian
  • 3,483
  • 7
  • 27
  • 45

4 Answers4

23

Another way to do it:

/[^\D2]/

Which means, not a non-digit or 2.

Stuart Wakefield
  • 6,294
  • 24
  • 35
15

You can match the range of numbers before and after two with [0-13-9], like this:

"4526".match(/[0-13-9]+/)
["45"]
"029".match(/[0-13-9]+/)
["0"]
"09218".match(/[0-13-9]+/)
["09"]
Lepidosteus
  • 11,779
  • 4
  • 39
  • 51
  • 1
    how regex recognize the difference between 1 & 13 in that range? – Mohammad Masoudian Jun 08 '13 at 12:10
  • 4
    @MohammadMasoudian Regex doesnot know '13' thirteen. I knows only as a single char. – Muthu Ganapathy Nathan Jun 08 '13 at 12:11
  • if i want to deny zero numbers too, how to do it? – Mohammad Masoudian Jun 08 '13 at 12:12
  • @MohammadMasoudian: just remove the zero from the range, `[13-9]` should do it. – Lepidosteus Jun 08 '13 at 12:13
  • `0-1`? You can just say `01`. – nnnnnn Jun 08 '13 at 12:13
  • @nnnnnn: I was mostly trying to give a generic solution so he understands how it works, to avoid questions like "how to do it with 5 instead of 2". But in this case yes, `01` could be used instead. – Lepidosteus Jun 08 '13 at 12:15
  • Fair enough. And for Mohammad: note that this (and all of the answers so far) will match on strings that contain other characters too as long as those digits are somewhere in there. E.g., the regex will match `"abcdef 1543 ghij 222"` (but it will just match the "1543" part). To ensure there are no other characters anywhere in the string you need to do something like `/^[13-9]*$/`. – nnnnnn Jun 08 '13 at 12:19
3

Or this is also the correct answer.

/(?!2)\d/

nab1x9
  • 31
  • 1
1

This RegExp works: /([013-9])/

Prakash GPz
  • 1,675
  • 4
  • 16
  • 27