[英]In Java, how do I check if a string consists of both letters and numbers, but only letters and numbers?
I tried this: 我尝试了这个:
private static void isLetterandNumberCombo(Tokens token) {
if (token.getContents().matches("^(?=.*[A-Z])(?=.*[0-9])[A-Z0-9]+$")){
token.setValid(false);
}
}
but the input 123f45 still does not set the token to valid as I thought it would 但输入123f45仍未按我认为的那样将令牌设置为有效
Your solution is fine. 您的解决方案很好。 You just need to add the case-insensitive flag (
(?i)
) to match lowercase letters. 您只需要添加不区分大小写的标志(
(?i)
)即可匹配小写字母。 And matches()
looks for a full match, so you don't need the anchors at the beginning and end: 并且
matches()
寻找完全匹配,因此您不需要在开头和结尾处使用锚点:
(?i)(?=.*[A-Z])(?=.*[0-9])[A-Z0-9]+
Give this a whirl 旋转一下
private static boolean isLetterandNumberCombo(Tokens token) {
String regex = "^[a-zA-Z0-9]+$";
Pattern pattern = Pattern.compile(regex);
return pattern.matcher(token.getContents()).matches();
}
You'll get back true or false if the token is valid. 如果令牌有效,则将返回true或false。
I would go with: 我会去:
^[A-Za-z\d]*(([A-Za-z]\d)|(\d[A-Za-z]))[A-Za-z\d]*$
The idea is that a valid string will have either a letter followed by a number or the opposite somewhere, and other optional letters or numbers before or after. 这个想法是,一个有效的字符串将在其后跟一个字母,后跟一个数字或相反的数字,以及其他可选的字母或数字。
A simple regex would do the job: 一个简单的正则表达式就可以完成这项工作:
Change your function to: 将功能更改为:
private static void isLetterandNumberCombo(Tokens token) {
token.setValid(token.getContents() != null && token.getContents().matches("[a-zA-Z0-9]+"));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.