Regex to match all permutations of {1,2,3,4} without repetition

Apoorv Saxena picture Apoorv Saxena · Jun 23, 2010 · Viewed 8.5k times · Source

I am implementing the following problem in ruby.

Here's the pattern that I want :

1234, 1324, 1432, 1423, 2341 and so on

i.e. the digits in the four digit number should be between [1-4] and should also be non-repetitive.

to make you understand in a simple manner I take a two digit pattern and the solution should be : 12, 21

i.e. the digits should be either 1 or 2 and should be non-repetitive.

To make sure that they are non-repetitive I want to use $1 for the condition for my second digit but its not working.

Please help me out and thanks in advance.

Answer

polygenelubricants picture polygenelubricants · Jun 23, 2010

You can use this (see on rubular.com):

^(?=[1-4]{4}$)(?!.*(.).*\1).*$

The first assertion ensures that it's ^[1-4]{4}$, the second assertion is a negative lookahead that ensures that you can't match .*(.).*\1, i.e. a repeated character. The first assertion is "cheaper", so you want to do that first.

References

Related questions