rookiecookie
rookiecookie

Reputation: 199

Regex for 9 unique digits separated by a space?

I'm trying to write a piece of validation code for an input of numbers. The numbers have to contain 0 to 8. The order does not matter, but the digits cannot be repeated.

E.g. 1 4 7 8 0 2 5 3 6 //valid 1 1 3 6 3 8 0 5 4 //invalid as 1 is repeated

I have a regex so far that takes in 9 unique digits:

 String pattern = "^(?!.*(.).*\\1)\\d{9}";

E.g. 123456780 //valid

112345678 //invalid as 1 is repeated

1 2 3 4 5 6 7 8 0 //invalid

All I need is to add the bit where it takes in the digits separated by a space!

Thanks.

Upvotes: 1

Views: 250

Answers (2)

Amadan
Amadan

Reputation: 198324

This is really abuse of regex :D but

^(?!.*(\d).*\1)(?:[0-8] ){8}[0-8]$

should do it. Make sure only digits are taken into consideration in the part where you disallow repetition; then you can have eight digit-space pairs followed by a digit at the end (with correct digits).

Upvotes: 3

achAmháin
achAmháin

Reputation: 4266

I'm not sure you need a regex for this. Consider using a Set:

Scanner sc = new Scanner(System.in);
Set<Integer> set = new HashSet<>();
int count = 0;
while (count < 9) {
    System.out.println("Enter a number:");
    int num = sc.nextInt();
    if (num >= 0 && num <= 8) {
        set.add(num);
    }
    count++;
}

System.out.println(set.size() == 9);

Or if your input comes in one go:

String[] nums = sc.nextLine().split("\\s+");
for (String num : nums) {
    set.add(Integer.parseInt(num));
}

You'll have to consider checking for invalid input. Or you could check the nums is 9 first before adding to set and return false then straight away.

Upvotes: 2

Related Questions