-1

I am trying to allow an input that is only made with characters a-zA-Z and also haves space. Example: "Chuck Norris". What happens with the code below is that the scanner input.next() doesn't allow the mentioned example input string.

I expect this output: Success! but this is the actual output: Again:

try {
    String input_nome = input.next();            // Source of the problem

    if (input_nome.matches("[a-zA-Z ]+")) {
        System.out.print("Success!");
        break;
    } else {
        System.err.print("Again: ");
    }
} catch (Exception e) {
    e.printStackTrace();
}

SOLUTION

The source of the problem is the used scanner method.

String input_nome = input.next();            // Incorrect scanner method
String input_nome = input.nextLine();        // Correct scanner method

Explanation: https://stackoverflow.com/a/22458766/11860800

Grinnex.
  • 199
  • 3
  • 11
  • 1
    As mentioned in one of the answers your code works fine so the issue is not related to your reg exp pattern if you get the wrong result. – Joakim Danielson Jul 31 '19 at 16:16

2 Answers2

2

String t = "Chuck Norris";

t.matches("[a-zA-Z ]+")

Does in fact return true. Check for your input that it actually is "Chuck Norris", and make sure the space is not some weird character. Also instead of space, you can use \s. I also recommend 101regex.com

user1478293
  • 46
  • 1
  • 5
1

Please refer this link : Java Regex to Validate Full Name allow only Spaces and Letters

you can use the below Regular Expression

String regx = "^[\\p{L} .'-]+$";

This should work for all scenarios and unicode.

Puru
  • 9
  • 4