Steve
Steve

Reputation: 4918

Matching any number except 1 with Regex

I have a regular expression now that matches any number:

/(\d)/

Now I'd like to modify it to not pick up 1, so it should capture 238, 12, 41, but not 1.

Does anyone see a way to do that?

Thanks

Upvotes: 3

Views: 1830

Answers (3)

hwnd
hwnd

Reputation: 70750

Assuming Negative Lookahead is supported you could do:

^(?!1$)\d+$

Or simply use the alternation operator in context placing what you want to exclude on the left-hand side, and place what you want to match in a capturing group on the right-hand side.

\b1\b|(\d+)

Live Demo

Upvotes: 5

Kirill Polishchuk
Kirill Polishchuk

Reputation: 56222

Use this regular expression

\b[02-9]\b|\d{2,}

Upvotes: 1

anhlc
anhlc

Reputation: 14469

You can use /(?!1$)\d+/ Try this code in PHP:

   $a ="1";
   $b ="2";
   $reg = "/(?!1$)\d+/";
   echo preg_match($reg, $a);
   echo preg_match($reg, $b);

Upvotes: 0

Related Questions