[0-8]{1, 1} matches one digit out of the set {0 1 2 3 4 5 6 7 8}, so it doesn't do what you need at all.Actually, I am not sure that you can do this in one regex. I will show a simpler example only using permutations of the digits 0 - 3 (to make it easier to follow): First you have to check that your string contains 4 digits in the range 0 - 3. That one is easy: /^[0-3]{4}$/ If your string passes this test, then you check whether each digit occurs only once. /^(\d)(?!\d*\1)(\d)(?!\d*\2)(\d)(?!\d*\3)\d$/;
This works by capturing each digit and using negative look-aheads to check that this digit does not re-occur again in the string.The following program proves that it works:
use warnings;
use strict;
for my $one (0 .. 3) {
for my $two (0 .. 3) {
for my $three (0 .. 3) {
for my $four (0 .. 4) {
my $test = "$one$two$three$four";
print "$test\n" if $test=~m/^[0-3]{4}$/ and $test=~m/^
+(\d)(?!\d*\1)(\d)(?!\d*\2)(\d)(?!\d*\3)\d$/;
}
}
}
}
Output:0123
0132
0213
0231
0312
0321
1023
1032
1203
1230
1302
1320
2013
2031
2103
2130
2301
2310
3012
3021
3102
3120
3201
3210
CountZero A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James
|