-4

Can someone tell me how to allow in Regex all a-zA-Z0-9 except 6 digits long number?

So true for:

1234567

a123456 

123456P

3A237bdb8

but false for

123456

I want to

allow only letters and digits

deny 6 digit long number (like 123456) and other not letter characters like -_+,.!@#$ etc.

Tom
  • 1,203
  • 3
  • 15
  • 35
  • 1
    See [Regex: match everything but specific pattern](https://stackoverflow.com/a/37988661/3832970) (scroll to *a string equal to some string*) – Wiktor Stribiżew Sep 17 '19 at 10:03
  • And note that the string can also be any regex, such as `\d{6}` – Maarten Bodewes Sep 17 '19 at 10:06
  • Possible duplicate of [Learning Regular Expressions](https://stackoverflow.com/questions/4736/learning-regular-expressions) – Biffen Sep 17 '19 at 10:10
  • My intent is to allow all letters and digits except exactly 6 digit long number. I do not want to allow space, dots, commas, and other characters that can be a string. – Tom Sep 17 '19 at 10:11
  • `$s =~ /^[a-zA-Z0-9]*$/ and $s !~ /^\d{6}$/`? – Biffen Sep 17 '19 at 10:12
  • @Biffen I know regex and I use it for a long time. I just don't know how to handle this particular case which is difficult to me to fulfil. I know that there are many materials about Regex but I don't know how to do it. – Tom Sep 17 '19 at 10:14
  • @Biffen thank you but this ^[a-zA-Z0-9]*$ allow all letter and digits but doesn't exclude 6 digit long number. This ^\d{6}$ works almost but allows characters like -_ etc. But I want to allow only a-zA-Z0-9 – Tom Sep 17 '19 at 10:19
  • @Tom They’re two different pattern for testing two different things. One should match and the other shouldn’t. Much easier to read than one complex pattern. – Biffen Sep 17 '19 at 10:22
  • 1
    How about: `^(?!\d{6}$)[a-zA-Z0-9]+$` [Demo](https://regex101.com/r/3UBqj3/1) – Toto Sep 17 '19 at 10:27
  • @Toto this is it!!! Thank you. Can you write this as an answer? So I had thought it in a wring way. I wanted to allow something and exclude something else while this was just a matter of excluding something from the beginning. This is great! – Tom Sep 17 '19 at 10:30

1 Answers1

0

If your regex engine supports lookahead, you can use:

^(?!\d{6}$)[a-zA-Z0-9]+$

Demo

Toto
  • 89,455
  • 62
  • 89
  • 125