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

旧时模样 提交于 2020-01-05 18:40:49

问题


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

}

回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/16430684/how-to-analyze-a-string-in-java-to-make-sure-that-it-has-both-letters-and-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!