Java正则表达式匹配字母数字字符串 [英] java regex match for alphanumeric string

查看:2084
本文介绍了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;

感谢帮助

推荐答案

您需要添加一个满足您要求的量词:*-0次或多次出现或+-1次或多次出现.您也可以省略^$并使用

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;

要匹配所有Unicode字母,请使用\p{L}类(也许还可以使用\p{M}来匹配变音符号):"[\\p{L}\\p{M}0-9]+".

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

login.getPassword().matches("[0-9a-zA-Z]*");login.getPassword().matches("[0-9a-zA-Z]");有什么区别?

仅当整个字符串仅包含 1位数字或字母时,.matches("[0-9a-zA-Z]")才会返回true. [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.

这篇关于Java正则表达式匹配字母数字字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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