0

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"?

Andrew
  • 2,571
  • 2
  • 31
  • 56

1 Answers1

3

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.
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 1
    Thanks for that and adding a bit extra explanation, I don't do them enough, but did see it call it a lookahead in regex101, many thanks – Andrew Oct 20 '21 at 15:13