0

In my code I want anything that isn't a three (or more) letter word to go into the while loop and anything else to continue into the code. I am not that confident with Regex and would like help on how to fix it.

    while (!(word.matches("(a-z){3,}")))
    {
        System.out.println("You have not entered in a valid word (it has to be at least 3 letters long).");

        System.out.println();

        System.out.print("Please enter a word of your choice: ");
        word = keyboard.nextLine();

    }

N.B. This is for homework

red_star_12
  • 37
  • 1
  • 8

1 Answers1

1

You need to use [a-z] whiich means a char between a and z, rather than (a-z) which means match exactly "a-z"


  • You'd better \w class that represents word-character = [a-zA-Z0-9_]
  • \w = a letter between a and z OR bewtween A and Z OR between 0 and 9, or a _

==> regex demo

while (!word.matches("\\w{3,}")) {  // don't match more than 3
   //
}

// -- OR --

while (word.matches("\\w{0,3}")) {  // match between 0 and 3 is also correct
   //
}
azro
  • 53,056
  • 7
  • 34
  • 70