如何分析java中的字符串以确保它有字母和数字? [英] How to analyze a string in java to make sure that it has both letters and numbers?

查看:124
本文介绍了如何分析java中的字符串以确保它有字母和数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在JAVA中分析一个字符串,以确定它是否包含字母和数字。所以这就是我到目前为止所拥有的。
变量pass是一个由用户输入的最多8个字符/数字的字符串。

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

}


推荐答案

您的问题有点模棱两可。

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]+$");

将返回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]*$");

所有最好的

这篇关于如何分析java中的字符串以确保它有字母和数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆