Validate a string only with the letters a and b, and containing at least one space

2

Hello community of StackOverflow, I commented that you have to validate a string entered from the keyboard that should only contain the letters a and b and have at least one space. With the code I have so far there is no problem with chains of type "abbaab abba", the problem is that it also validates the strings that do not have space, what do I have to add so that it no longer validates the strings that do not have space? '

Scanner entrada = new Scanner(System.in);

String cadena = entrada.nextLine();

Pattern rango = Pattern.compile("[^A-Ba-b ]");

Matcher cadenaValida = rango.matcher(cadena);

    if (!cadenaValida.find()) 
        System.out.println("La cadena que ingresaste es valida");

    else
        System.out.println("La cadena no es valida");
    
asked by Jose Armando Lopez Alvarez 12.10.2018 в 07:04
source

2 answers

0

I think with the following code you get it:

Scanner entry = new Scanner (System.in);

String string = input.nextLine ();

Pattern rango = Pattern.compile("([a|b]*\s[a|b]*)*");

Matcher cadenaValida = rango.matcher(cadena);

    if (cadenaValida.matches()) 
        System.out.println("La cadena que ingresaste es valida");

    else
        System.out.println("La cadena no es valida");
    }

Keep in mind that you must use matches instead of find, to avoid that they only match substrings. The \ s indicates the space character

    
answered by 12.10.2018 / 08:38
source
0

boolean. boolean found = matcher.find (); String stringConResult = (found)? "The string you entered is valid": "The string is NOT valid";

    
answered by 12.10.2018 в 11:05