Home > Enterprise >  Regex to allow all but the character 0 on its own
Regex to allow all but the character 0 on its own

Time:10-21

I want to create a regex to that will allow numbers and or characters but not 0 (zero) on its own.

This is what I have so far whilst playing with regex101.com

/^([^0])([a-z1-9])*$/img

It matches the last 3 items but I also need it to match the 00 one.

0
00
12
22344
sometext

How can I do this, how can I write "if its 0 on its own I don't want it, but anything else I do want it"?

CodePudding user response:

You can use a negative lookahead to disallow just 0 and then match 1 alphanumeric in the match to allow matching 0s:

^(?!0$)[a-z\d] $

RegEx Demo

  • (?!0$) is negative lookahead after start position so that we fail the match if just 0 appears in input.
  • [a-z\d] matches 1 or more of a lowercase letter or a digit.
  • Related