Search code examples
javaregexstringif-statementcomparison-operators

How to analyze a string in java to make sure that it has both letters and numbers?


I need to analyze a string in JAVA to find out if it has both letters and numbers. So this is what I have so far. The variable pass is a String of maximum 8 characters/numbers that is inputted by the user.

if(pass.matches("[^A-Za-z0-9]"))

{

System.out.println("Valid"); 

}

else

{

   System.out.println("Invalid");

}

Solution

  • Your question is a little ambiguous.

    If you just want to know whether the string contains letters or numbers (but perhaps only letters or only numbers) and nothing else, then the regex :

    pass.matches("^[a-zA-Z0-9]+$");
    

    will return true.

    If you want to check whether it contains both letters and numbers, and nothing else, then it is more complex, but something like:

    pass.matches("^[a-zA-Z0-9]*(([a-zA-Z][0-9])|([0-9][a-zA-Z]))[a-zA-Z0-9]*$");
    

    all the best