Why regex pattern [1-3]\s+[1-3] doesn’t match two numbers separated with whitespaces when used in code

Tags: ,



As a part of my project I have a method that checks and returns user input (from console, System.in) if it’s correct (and asks for input again if it’s not). Correct input is a pair of digits between 1 and 3 (inclusively) separated with whitespaces. To check input I’m using hasNext(String pattern) method from class Scanner with regex pattern [1-3]\s+[1-3] (so that amount of whitespaces doesn’t matter).

All of the online regex-testers prove this pattern working if there’s one backslash ([1-3]s+[1-3]). For example: https://regexr.com/58bh6 and https://regex101.com/r/zcwpNx/1. After making some research I found out that in java you have to escape the escape character to make it work (which is really confusing), hence there has to be two backslashes. This one even shows conversion from one to two backslashes for Java https://www.regexplanet.com/share/index.html?share=yyyydmcrhnr

The problem is: it doesn’t want to work like this. It doesn’t want to work either way. If there is one backslash I get compile error and if there are two the method just doesn’t accept input (https://onlinegdb.com/H1Ssexqkw). I’ve also tried using three and four backslashes but got no success.

The whole method is there:

    private static byte[] checkAndGetMoveInput(Scanner input){
        byte x = -1, y = -1;

        System.out.print("Enter the coordinates: ");
        Scanner _input = new Scanner(input.nextLine());

        if (_input.hasNext("[0-9]+")){
            if (_input.hasNext("[1-3]\s+[1-3]")) {
                x = _input.nextByte();
                y = _input.nextByte();
            } else {
                System.out.println("Coordinates should be from 1 to 3!");
                checkAndGetMoveInput(input);
            }
        } else {
            System.out.println("You should enter numbers!");
            checkAndGetMoveInput(input);
        }

        return new byte[]{x, y};
    }

Sorry, if I’m missing something obvious but what am I doing wrong? And how to do it right?

Answer

As mentioned by andreoss, you need to change delimiter, also there is a mistake in recursion. Here is the modified code:

private static byte[] checkAndGetMoveInput(Scanner input) {
    System.out.print("Enter the coordinates: ");
    Scanner _input = new Scanner(input.nextLine());
    _input.useDelimiter("$");

    if (_input.hasNext("[0-9]+\s+[0-9]+")) {
        if (_input.hasNext("[1-3]\s+[1-3]")) {
            _input.useDelimiter("\s");
            byte x = _input.nextByte();
            byte y = _input.nextByte();
            return new byte[]{x, y};
        } else {
            System.out.println("Coordinates should be from 1 to 3!");
            return checkAndGetMoveInput(input);
        }
    } else {
        System.out.println("You should enter numbers!");
        return checkAndGetMoveInput(input);
    }
}


Source: stackoverflow