DevilaN DevilaN - 1 month ago 8
MySQL Question

How to match number composed of at least 4 unique digits

I need (unfortunately it has to be done in MySQL) to verify using regular expression numbers using rule that number have to be composed of at least 4 unique digits.

Examples what i need to accomplish:

112233441122 is OK (made only from 1,2,3,4)
1234564222134 is OK (6 different digits)
122102111 is bad (3 digits only: 0,1,2)
91511201 is OK (5 digits)


I would gladly share my tries, but I am not good right now with backreferences, and not any of my puny tries got even closer to match word composed from even two different characters.
I've also tried user defined functions that count characters in string, but they are slow and not so elegant as using REGEX.

Answer

Assuming that you are using a regex engine that supports backreferences and possesive matching, you can use:

^(\d)\1*+(\d)(?:\1|\2)*+(\d)(?:\1|\2|\3)*+\d+$

The same can be done using atomic groups:

^(\d)(?>\1*)(\d)(?>(?:\1|\2)*)(\d)(?>(?:\1|\2|\3)*)\d+$