java正则匹配字母,Java正则表达式匹配字母数字字符串

I am trying to check whether a password is alphanumeric or not using regex

but I am not getting the result I expect. What is the problem with the below code?

boolean passwordOnlyAlphaNumericCheck = false;

Pattern patternAlphaNumericCheck = Pattern.compile("^[a-zA-Z0-9]$");

Matcher matcherAlphaNumericCheck = patternAlphaNumericCheck.matcher(login.getPassword());

if(matcherAlphaNumericCheck.find())

passwordOnlyAlphaNumericCheck = true;

Thanks for help

解决方案

You need to add a quantifier that suits your requirements: * - 0 or more occurrences or + - 1 or more occurrences. You can also omit the ^ and $ and use String.matches():

boolean passwordOnlyAlphaNumericCheck = false;

if(login.getPassword().matches("[a-zA-Z0-9]*"))

passwordOnlyAlphaNumericCheck = true;

To match all Unicode letters, use \p{L} class (and perhaps, \p{M} to match diacritics): "[\\p{L}\\p{M}0-9]+".

what is the difference between login.getPassword().matches("[0-9a-zA-Z]*"); and login.getPassword().matches("[0-9a-zA-Z]");?

The .matches("[0-9a-zA-Z]") will only return true if the whole string contains just 1 digit or letter. The * in [0-9a-zA-Z]* will allow an empty string, or a string having zero or more letters/digits.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值