vendredi 27 mars 2015

How to use a regular expression to check for duplicate characters in a string?


Vote count:

0




I am coding a trivia game in Java, and I have everything done except for validating one part of the user's answer. So basically, I will prompt the user with the question and the possible answers, and the user will enter their answer. Right now, I am trying to validate their answer before I check if it is correct so if it is wrong, I can prompt them to enter a different answer. The rules are that their answer has to be a string from zero to four characters, using only the digits 1-4, and there can't be repeated characters. So 1234 is valid, 24 is valid, 321 is valid, 589 is invalid, abc is invalid, 111 is invalid, and 1233 is invalid. So far I have gotten every condition covered except for the duplicate characters. At first I used



if (answer.matches("^[1-4]{0,4}$")) { // valid check if correct


This takes care of everything but the duplicates. Next I tried



if (answer.matches("^1?2?3?4?$")) { // valid check if correct


This takes care of the duplicates IF the user enters the number in ascending order, i.e. 123, 234, 24, 12, 2344, etc. The only problem is that if the user enters something like 432, it will be considered invalid even though it should be considered valid. I get why that doesn't match my regex, but the only other solution I could think of would be to list all possible solutions, but obviously I'm not going to put 24 conditions in my if statement. Is there anything I can do with regex's that I could do to fix this? I know I could do this in a brute force fashion, but I'd much rather have an efficient regex to solve this. Thanks.



asked 1 min ago







How to use a regular expression to check for duplicate characters in a string?

Aucun commentaire:

Enregistrer un commentaire