如何检查字符串是否仅包含数字和字母,即。是字母数字吗?
答案 0 :(得分:73)
考虑到您要检查ASCII字母数字字符,请尝试以下操作:
"^[a-zA-Z0-9]*$"
。在String.matches(Regex)
中使用此RegEx,如果字符串是字母数字,则返回true,否则返回false。
public boolean isAlphaNumeric(String s){
String pattern= "^[a-zA-Z0-9]*$";
return s.matches(pattern);
}
如果有帮助,请阅读此内容以获取有关正则表达式的更多详细信息:http://www.vogella.com/articles/JavaRegularExpressions/article.html
答案 1 :(得分:24)
为了兼容unicode:
^[\pL\pN]+$
,其中
\pL stands for any letter
\pN stands for any number
答案 2 :(得分:11)
这是2016年或更晚,事情已经取得了进展。这匹配Unicode字母数字字符串:
^[\\p{IsAlphabetic}\\p{IsDigit}]+$
请参阅the reference(“Unicode脚本,块,类别和二进制属性的类”一节)。还有this answer我觉得有帮助。
答案 3 :(得分:9)
请参阅Pattern的文档。
假设US-ASCII字母表(a-z,A-Z),您可以使用\p{Alnum}
。
检查一行只包含此类字符的正则表达式为"^[\\p{Alnum}]*$"
。
这也匹配空字符串。要排除空字符串:"^[\\p{Alnum}]+$"
。
答案 4 :(得分:5)
使用字符类:
^[[:alnum:]]*$
答案 5 :(得分:3)
Pattern pattern = Pattern.compile("^[a-zA-Z0-9]*$");
Matcher matcher = pattern.matcher("Teststring123");
if(matcher.matches()) {
// yay! alphanumeric!
}
答案 6 :(得分:1)
为only alpha and num with one char at-least
尝试此[0-9a-zA-Z] + ..
可能需要修改以便对其进行测试
http://www.regexplanet.com/advanced/java/index.html
Pattern pattern = Pattern.compile("^[0-9a-zA-Z]+$");
Matcher matcher = pattern.matcher(phoneNumber);
if (matcher.matches()) {
}
答案 7 :(得分:0)
100%字母数字RegEx(它只包含字母数字,甚至不包含整数和字符,只包含字母数字)
例如:
特殊字符(不允许)
123(不允许)
asdf(不允许)
1235asdf(允许)
String name="^[^<a-zA-Z>]\\d*[a-zA-Z][a-zA-Z\\d]*$";
答案 8 :(得分:0)
如果您还希望包含外语字母,则可以尝试:
String string = "hippopotamus";
if (string.matches("^[\\p{L}0-9']+$")){
string is alphanumeric do something here...
}
或者如果您想允许特定的特殊字符,但不允许其他字符。例如,对于#或 space ,您可以尝试:
String string = "#somehashtag";
if(string.matches("^[\\p{L}0-9'#]+$")){
string is alphanumeric plus #, do something here...
}
答案 9 :(得分:0)
要考虑所有 Unicode 字母和数字,可以使用 Character.isLetterOrDigit
。在 Java 8 中,这可以与 String#codePoints
和 IntStream#allMatch
结合使用。
boolean alphanumeric = str.codePoints().allMatch(Character::isLetterOrDigit);
答案 10 :(得分:0)
要包含 [a-zA-Z0-9_]
,您可以使用 \w
。
所以myString.matches("\\w*")
。 (.matches
必须匹配整个字符串,因此不需要 ^\\w*$
。.find
可以匹配子字符串)
https://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html
答案 11 :(得分:-3)
要检查字符串是否为字母数字,可以使用遍历字符串中每个字符并检查其是否为字母数字的方法。
public static boolean isAlphaNumeric(String s){
for(int i = 0; i < s.length(); i++){
char c = s.charAt(i);
if(!Character.isDigit(c) && !Character.isLetter(c))
return false;
}
return true;
}