Pregunta

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");

}
¿Fue útil?

Solución

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

Otros consejos

I'd use StringUtils.isAlphanumeric. Your code will look like this:

if (StringUtils.isAlphanumeric(pass)) {
    //valid
} ...

You say you also want a maximum of 8 characters. You can do it like this:

if (StringUtils.isAlphanumeric(pass) && StringUtils.length(pass) <= 8) {
    //valid
} ...

The advantage of using StringUtils again for the length is that you won't get a NullPointerException if pass is null. Alternatively, you could just use pass.length(), but you risk getting a NullPointerException.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top