Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex pattern that matches any number include 1-9 except 2

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.

like image 702
Mohammad Masoudian Avatar asked Jun 08 '13 12:06

Mohammad Masoudian


People also ask

How do I match a specific number in regex?

To match any number from 0 to 9 we use \d in regex. It will match any single digit number from 0 to 9. \d means [0-9] or match any number from 0 to 9. Instead of writing 0123456789 the shorthand version is [0-9] where [] is used for character range.

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string).

What does 9 mean in regex?

In a regular expression, if you have [a-z] then it matches any lowercase letter. [0-9] matches any digit. So if you have [a-z0-9], then it matches any lowercase letter or digit.

How do you define a number range in regex?

Example: Regex Number Range 1-20 Range 1-20 has both single digit numbers (1-9) and two digit numbers (10-20). For double digit numbers we have to split the group in two 10-19 (or in regex: "1[0-9]") and 20. Then we can join all these with an alternation operator to get "([1-9]|1[0-9]|20)".


2 Answers

Another way to do it:

/[^\D2]/

Which means, not a non-digit or 2.

like image 81
Stuart Wakefield Avatar answered Sep 30 '22 19:09

Stuart Wakefield


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"]
like image 34
Lepidosteus Avatar answered Sep 30 '22 19:09

Lepidosteus